List of usage examples for org.w3c.dom NamedNodeMap getLength
public int getLength();
From source file:Main.java
private static void renderNode(StringBuffer sb, Node node, String margin, String indent, String lab, String rab, String nl) {/*from www .j ava2 s .c o m*/ if (node == null) { sb.append("null"); return; } switch (node.getNodeType()) { case Node.DOCUMENT_NODE: //sb.append(margin + lab +"?xml version=\"1.0\" encoding=\"UTF-8\"?" + rab + nl); Node root = ((Document) node).getDocumentElement(); renderNode(sb, root, margin, indent, lab, rab, nl); break; case Node.ELEMENT_NODE: String name = getNodeNameWithNamespace(node); NodeList children = node.getChildNodes(); int nChildren = children.getLength(); NamedNodeMap attributes = node.getAttributes(); int nAttrs = attributes.getLength(); boolean singleShortTextChild = (nAttrs == 0) && (nChildren == 1) && (children.item(0).getNodeType() == Node.TEXT_NODE) && (children.item(0).getTextContent().length() < 70) && (!children.item(0).getTextContent().contains("\n")); if (singleShortTextChild) { sb.append(margin + lab + name + ((nChildren == 0) ? "/" : "") + rab); } else if (nAttrs == 0 && !singleShortTextChild) { sb.append(margin + lab + name + ((nChildren == 0) ? "/" : "") + rab + nl); } else if (nAttrs == 1) { Node attr = attributes.item(0); String attrName = getNodeNameWithNamespace(attr); sb.append(margin + lab + name + " " + attrName + "=\"" + escapeChars(attr.getNodeValue()) + "\"" + ((nChildren == 0) ? "/" : "") + rab + nl); } else { sb.append(margin + lab + name + nl); for (int i = 0; i < nAttrs; i++) { Node attr = attributes.item(i); String attrName = getNodeNameWithNamespace(attr); sb.append(margin + indent + attrName + "=\"" + escapeChars(attr.getNodeValue())); if (i < nAttrs - 1) sb.append("\"" + nl); else sb.append("\"" + ((nChildren == 0) ? "/" : "") + rab + nl); } } if (singleShortTextChild) { String text = escapeChars(node.getTextContent()); sb.append(text.trim()); sb.append(lab + "/" + name + rab + nl); } else { for (int i = 0; i < nChildren; i++) { renderNode(sb, children.item(i), margin + indent, indent, lab, rab, nl); } } if (nChildren != 0 && !singleShortTextChild) sb.append(margin + lab + "/" + name + rab + nl); break; case Node.TEXT_NODE: String text = escapeChars(node.getNodeValue()); String[] lines = text.split("\n"); for (String line : lines) { line = line.trim(); if (!line.equals("")) sb.append(margin + line + nl); } break; case Node.CDATA_SECTION_NODE: String cdataText = node.getNodeValue(); String[] cdataLines = cdataText.split("\n"); sb.append(margin + lab + "![CDATA[" + nl); for (String line : cdataLines) { line = line.trim(); if (!line.equals("")) sb.append(margin + indent + line + nl); } sb.append(margin + "]]" + rab + nl); break; case Node.PROCESSING_INSTRUCTION_NODE: sb.append(margin + lab + "?" + node.getNodeName() + " " + escapeChars(node.getNodeValue()) + "?" + rab + nl); break; case Node.ENTITY_REFERENCE_NODE: sb.append("&" + node.getNodeName() + ";"); break; case Node.DOCUMENT_TYPE_NODE: // Ignore document type nodes break; case Node.COMMENT_NODE: sb.append(margin + lab + "!--" + node.getNodeValue() + "--" + rab + nl); break; } return; }
From source file:ee.ria.xroad.proxy.util.MetaserviceTestUtil.java
/** Merge xroad-specific {@link SoapHeader} to the generic {@link SOAPHeader} * @param header/*ww w . ja v a 2s . c o m*/ * @param xrHeader * @throws JAXBException * @throws ParserConfigurationException * @throws SOAPException */ public static void mergeHeaders(SOAPHeader header, SoapHeader xrHeader) throws JAXBException, ParserConfigurationException, SOAPException { Document document = documentBuilderFactory.newDocumentBuilder().newDocument(); final DocumentFragment documentFragment = document.createDocumentFragment(); // marshalling on the header would add the xroad header as a child of the header // (i.e. two nested header elements) marshaller.marshal(xrHeader, documentFragment); Document headerDocument = header.getOwnerDocument(); Node xrHeaderElement = documentFragment.getFirstChild(); assertTrue("test setup failed: assumed had header element but did not", xrHeaderElement.getNodeType() == Node.ELEMENT_NODE && xrHeaderElement.getLocalName().equals("Header")); final NamedNodeMap attributes = xrHeaderElement.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { final Attr attribute = (Attr) attributes.item(i); header.setAttributeNodeNS((Attr) headerDocument.importNode(attribute, false)); } } final NodeList childNodes = xrHeaderElement.getChildNodes(); if (childNodes != null) { for (int i = 0; i < childNodes.getLength(); i++) { final Node node = childNodes.item(i); header.appendChild(headerDocument.importNode(node, true)); } } }
From source file:eu.europa.ec.markt.dss.validation102853.xml.XmlNode.java
/** * @param xmlNode the {@code XmlNode} to which the element is added * @param element the {@code Node} to be copied *//*w ww.j ava 2 s.c om*/ private static void recursiveCopy(final XmlNode xmlNode, final Node element) { final String name = element.getNodeName(); final XmlNode _xmlNode = new XmlNode(name); final NamedNodeMap attributes = element.getAttributes(); for (int jj = 0; jj < attributes.getLength(); jj++) { final Node attrNode = attributes.item(jj); final String attrName = attrNode.getNodeName(); if (!"xmlns".equals(attrName)) { _xmlNode.setAttribute(attrName, attrNode.getNodeValue()); } } final NodeList nodes = element.getChildNodes(); boolean hasElementNodes = false; for (int ii = 0; ii < nodes.getLength(); ii++) { final Node node = nodes.item(ii); if (node.getNodeType() == Node.ELEMENT_NODE) { hasElementNodes = true; recursiveCopy(_xmlNode, node); } } if (!hasElementNodes) { final String value = element.getTextContent(); _xmlNode.setValue(value); } _xmlNode.setParent(xmlNode); }
From source file:com.portfolio.data.utils.DomUtils.java
public static String getNodeAttributesString(Node node) { String ret = ""; NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attribute = (Attr) attributes.item(i); ret += attribute.getName().trim() + "=\"" + StringEscapeUtils.escapeXml11(attribute.getValue().trim()) + "\" "; }/* w w w .j a v a2 s. com*/ return ret; }
From source file:com.example.soaplegacy.XmlUtils.java
public static String removeUnneccessaryNamespaces(String xml) { if (StringUtils.isBlank(xml)) { return xml; }/*from w ww . ja v a2 s .com*/ XmlObject xmlObject = null; XmlCursor cursor = null; try { xmlObject = XmlObject.Factory.parse(xml); cursor = xmlObject.newCursor(); while (cursor.currentTokenType() != XmlCursor.TokenType.START && cursor.currentTokenType() != XmlCursor.TokenType.ENDDOC) { cursor.toNextToken(); } if (cursor.currentTokenType() == XmlCursor.TokenType.START) { Map<?, ?> nsMap = new HashMap<Object, Object>(); cursor.getAllNamespaces(nsMap); nsMap.remove(cursor.getDomNode().getPrefix()); NamedNodeMap attributes = cursor.getDomNode().getAttributes(); for (int c = 0; attributes != null && c < attributes.getLength(); c++) { nsMap.remove(attributes.item(c).getPrefix()); } if (cursor.toFirstChild()) { while (cursor.getDomNode() != xmlObject.getDomNode()) { attributes = cursor.getDomNode().getAttributes(); for (int c = 0; attributes != null && c < attributes.getLength(); c++) { nsMap.remove(attributes.item(c).getPrefix()); } nsMap.remove(cursor.getDomNode().getPrefix()); cursor.toNextToken(); } } xml = xmlObject.xmlText( new XmlOptions().setSaveOuter().setSavePrettyPrint().setSaveImplicitNamespaces(nsMap)); } } catch (XmlException e) { } finally { if (cursor != null) cursor.dispose(); } return xml; }
From source file:com.wavemaker.tools.pws.install.PwsInstall.java
private static Document insertEntryKey(Document doc, File[] runtimeJarFiles, File[] toolsJarFiles, String partnerName) throws IOException { NodeList beans_list = doc.getElementsByTagName("beans"); Node beans_node = beans_list.item(0); // First delete old entries NodeList beansChildren = beans_node.getChildNodes(); Node bean_node = null, prop_node = null, map_node = null; for (int i = 0; i < beansChildren.getLength(); i++) { if (!beansChildren.item(i).getNodeName().equals("bean")) { continue; }//from www . ja v a2 s .co m bean_node = beansChildren.item(i); NodeList beanChildren = bean_node.getChildNodes(); for (int j = 0; j < beanChildren.getLength(); j++) { if (!beanChildren.item(j).getNodeName().equals("property")) { continue; } prop_node = beanChildren.item(j); break; } if (prop_node == null) { continue; } NodeList propChildren = prop_node.getChildNodes(); for (int k = 0; k < propChildren.getLength(); k++) { if (!propChildren.item(k).getNodeName().equals("map")) { continue; } map_node = propChildren.item(k); break; } if (map_node == null) { continue; } NodeList mapChildren = map_node.getChildNodes(); List<Node> oldEntryList = new ArrayList<Node>(); for (int l = 0; l < mapChildren.getLength(); l++) { if (!mapChildren.item(l).getNodeName().equals("entry")) { continue; } Node target = mapChildren.item(l); NamedNodeMap entry_attributes = target.getAttributes(); for (int m = 0; m < entry_attributes.getLength(); m++) { Node entryAttr = entry_attributes.item(m); if (entryAttr.getNodeName().equals("key") && entryAttr.getNodeValue().equals(partnerName)) { oldEntryList.add(target); break; } } } if (oldEntryList.size() > 0) { for (Node oldEntry : oldEntryList) { map_node.removeChild(oldEntry); } } // Now, add new entries NamedNodeMap bean_attributes = bean_node.getAttributes(); for (int m = 0; m < bean_attributes.getLength(); m++) { Node beanAttr = bean_attributes.item(m); if (beanAttr.getNodeName().equals("id") && beanAttr.getNodeValue().equals("pwsLoginManagerBeanFactory")) { if (classExistsInJar(runtimeJarFiles, partnerName, LOGIN_MANAGER) || classExistsInJar(toolsJarFiles, partnerName, LOGIN_MANAGER)) { Element newEntry = doc.createElement("entry"); newEntry.setAttribute("key", partnerName); newEntry.setAttribute("value-ref", partnerName + LOGIN_MANAGER); map_node.appendChild(newEntry); } break; } else if (beanAttr.getNodeName().equals("id") && beanAttr.getNodeValue().equals("pwsRestImporterBeanFactory")) { if (classExistsInJar(runtimeJarFiles, partnerName, REST_IMPORTER) || classExistsInJar(toolsJarFiles, partnerName, REST_IMPORTER)) { Element newEntry = doc.createElement("entry"); newEntry.setAttribute("key", partnerName); newEntry.setAttribute("value-ref", partnerName + REST_IMPORTER); map_node.appendChild(newEntry); } break; } else if (beanAttr.getNodeName().equals("id") && beanAttr.getNodeValue().equals("pwsRestWsdlGeneratorBeanFactory")) { if (classExistsInJar(runtimeJarFiles, partnerName, REST_WSDL_GENERATOR) || classExistsInJar(toolsJarFiles, partnerName, REST_WSDL_GENERATOR)) { Element newEntry = doc.createElement("entry"); newEntry.setAttribute("key", partnerName); newEntry.setAttribute("value-ref", partnerName + REST_WSDL_GENERATOR); map_node.appendChild(newEntry); } break; } else if (beanAttr.getNodeName().equals("id") && beanAttr.getNodeValue().equals("pwsServiceModifierBeanFactory")) { if (classExistsInJar(runtimeJarFiles, partnerName, SERVICE_MODIFIER) || classExistsInJar(toolsJarFiles, partnerName, SERVICE_MODIFIER)) { Element newEntry = doc.createElement("entry"); newEntry.setAttribute("key", partnerName); newEntry.setAttribute("value-ref", partnerName + SERVICE_MODIFIER); map_node.appendChild(newEntry); } break; } else if (beanAttr.getNodeName().equals("id") && beanAttr.getNodeValue().equals("pwsRestServiceGeneratorBeanFactory")) { if (classExistsInJar(runtimeJarFiles, partnerName, REST_SERVICE_IMPORTER) || classExistsInJar(toolsJarFiles, partnerName, REST_SERVICE_IMPORTER)) { Element newEntry = doc.createElement("entry"); newEntry.setAttribute("key", partnerName); newEntry.setAttribute("value-ref", partnerName + REST_SERVICE_IMPORTER); map_node.appendChild(newEntry); } break; } else if (beanAttr.getNodeName().equals("id") && beanAttr.getNodeValue().equals("pwsResponseProcessorBeanFactory")) { if (classExistsInJar(runtimeJarFiles, partnerName, RESPONSE_PROCESSOR) || classExistsInJar(toolsJarFiles, partnerName, RESPONSE_PROCESSOR)) { Element newEntry = doc.createElement("entry"); newEntry.setAttribute("key", partnerName); newEntry.setAttribute("value-ref", partnerName + RESPONSE_PROCESSOR); map_node.appendChild(newEntry); } break; } } } return doc; }
From source file:Main.java
/** * Convert the given Node to an XML String. * <p>/* ww w . j a va 2 s.c o m*/ * This method is a simplified version of... * <p> * <code> * ByteArrayOutputStream out = new ByteArrayOutputStream();<br/> * javax.xml.Transformer transformer = TransformerFactory.newInstance().newTransformer();<br/> * transformer.transform( new DOMSource( node ), new StreamResult( out ));<br/> * return out.toString(); * </code> * <p> * ...but not all platforms (eg. Android) support <code>javax.xml.transform.Transformer</code>. * * @param indent * how much to indent the output. -1 for no indent. */ private static String nodeToString(Node node, int indent) { // Text nodes if (node == null) { return null; } if (!(node instanceof Element)) { String value = node.getNodeValue(); if (value == null) { return null; } return escapeForXml(value.trim()); } // (use StringBuffer for J2SE 1.4 compatibility) StringBuffer buffer = new StringBuffer(); // Open tag indent(buffer, indent); String nodeName = escapeForXml(node.getNodeName()); buffer.append("<"); buffer.append(nodeName); // Changing namespace String namespace = node.getNamespaceURI(); Node parentNode = node.getParentNode(); if (namespace != null && (parentNode == null || !namespace.equals(parentNode.getNamespaceURI()))) { buffer.append(" xmlns=\""); buffer.append(namespace); buffer.append("\""); } // Attributes NamedNodeMap attributes = node.getAttributes(); // Always put name first for easy unit tests Node name = attributes.getNamedItem("name"); if (name != null) { buffer.append(" name=\""); buffer.append(escapeForXml(name.getNodeValue())); buffer.append("\""); } for (int loop = 0; loop < attributes.getLength(); loop++) { Node attribute = attributes.item(loop); String attributeName = attribute.getNodeName(); // (I'm a bit surprised xmlns is an attribute - is that a bug?) if ("xmlns".equals(attributeName)) { continue; } // (always put name first for easy unit tests) if ("name".equals(attributeName)) { continue; } buffer.append(" "); buffer.append(escapeForXml(attributeName)); buffer.append("=\""); buffer.append(escapeForXml(attribute.getNodeValue())); buffer.append("\""); } // Children (if any) NodeList children = node.getChildNodes(); int length = children.getLength(); if (length == 0) { buffer.append("/>"); } else { buffer.append(">"); int nextIndent = indent; if (indent != -1) { nextIndent++; } for (int loop = 0; loop < length; loop++) { Node childNode = children.item(loop); if (indent != -1 && childNode instanceof Element) { buffer.append("\n"); } buffer.append(nodeToString(childNode, nextIndent)); } if (indent != -1 && buffer.charAt(buffer.length() - 1) == '>') { buffer.append("\n"); indent(buffer, indent); } // Close tag buffer.append("</"); buffer.append(nodeName); buffer.append(">"); } return buffer.toString(); }
From source file:com.esri.geoevent.solutions.adapter.cot.CoTUtilities.java
private static ArrayList<CoTTypeDef> typeBreakdown(Node n) { ArrayList<CoTTypeDef> hash = new ArrayList<CoTTypeDef>(); try {//from w w w . j av a 2s .com String name = n.getNodeName(); if (name.startsWith("#")) { // no match here return new ArrayList<CoTTypeDef>(); } StringBuffer sb = new StringBuffer(); sb.append('<').append(name); NamedNodeMap attrs = n.getAttributes(); if (attrs != null) { if (attrs.getLength() >= 3 && name.equals("cot")) { String zero = attrs.item(0).getNodeName(); String one = attrs.item(1).getNodeName(); String two = attrs.item(2).getNodeName(); // for some reason the attributes are not coming back in // order. make sure we get the ones we want int k = 0; int v = 1; if (zero.equals("cot")) { k = 0; } else if (one.equals("cot")) { k = 1; } else if (two.equals("cot")) { k = 2; } if (zero.equals("desc")) { v = 0; } else if (one.equals("desc")) { v = 1; } else if (two.equals("desc")) { v = 2; } hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(), false)); } else if (attrs.getLength() == 2 && name.equals("cot")) { String zero = attrs.item(0).getNodeName(); // make sure we are grabbing the elements in the right order int k = 0; int v = 1; if (zero.equals("cot")) { k = 0; v = 1; } else { k = 1; v = 0; } hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(), false)); } else if (attrs.getLength() == 2 && name.equals("weapon")) { String zero = attrs.item(0).getNodeName(); // make sure we are grabbing the elements in the right order int k = 0; int v = 1; if (zero.equals("cot")) { k = 0; v = 1; } else { k = 1; v = 0; } hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(), false)); } else if (attrs.getLength() == 2 && name.equals("relation")) { String zero = attrs.item(0).getNodeName(); // make sure we are grabbing the elements in the right order int k = 0; int v = 1; if (zero.equals("cot")) { k = 0; v = 1; } else { k = 1; v = 0; } hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(), false)); } else if (attrs.getLength() == 2 && name.equals("how")) { String zero = attrs.item(0).getNodeName(); // make sure we are grabbing the elements in the right order int k = 0; int v = 1; if (zero.equals("value")) { k = 0; v = 1; } else { k = 1; v = 0; } hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(), false)); } else if (attrs.getLength() == 2 && name.equals("is")) { String zero = attrs.item(0).getNodeName(); // make sure we are grabbing the elements in the right order int k = 0; int v = 1; if (zero.equals("match")) { k = 0; v = 1; } else { k = 1; v = 0; } String s = attrs.item(v).getNodeValue(); if (!(s.equals("true") || s.equals("false") || s.equals("spare") || s.equals("any") || s.equals("atoms"))) { hash.add(new CoTTypeDef(attrs.item(k).getNodeValue(), attrs.item(v).getNodeValue(), true)); } } else if (attrs.getLength() == 2 && name.equals("how")) { String zero = attrs.item(0).getNodeName(); // make sure we are grabbing the elements in the right order int k = 0; int v = 1; if (zero.equals("value")) { k = 0; v = 1; } else { k = 1; v = 0; } String s = attrs.item(v).getNodeValue(); if (!(s.equals("true") || s.equals("false") || s.equals("spare") || s.equals("any") || s.equals("atoms"))) { hash.add(new CoTTypeDef(attrs.item(k).getNodeValue(), attrs.item(v).getNodeValue(), false)); } } } String textContent = null; NodeList children = n.getChildNodes(); if (children.getLength() == 0) { if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) { } else { } } else { boolean hasValidChildren = false; for (int i = 0; i < children.getLength(); i++) { ArrayList<CoTTypeDef> childHash = typeBreakdown(children.item(i)); if (childHash.size() > 0) { hash.addAll(childHash); hasValidChildren = true; } } if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) { } } return hash; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return hash; } }
From source file:microsoft.exchange.webservices.data.core.EwsServiceXmlWriter.java
/** * @param element DOM element//from w w w .j a va 2 s .c om * @param writer XML stream writer * @throws XMLStreamException the XML stream exception */ public static void addElement(Element element, XMLStreamWriter writer) throws XMLStreamException { String nameSpace = element.getNamespaceURI(); String prefix = element.getPrefix(); String localName = element.getLocalName(); if (prefix == null) { prefix = ""; } if (localName == null) { localName = element.getNodeName(); if (localName == null) { throw new IllegalStateException("Element's local name cannot be null!"); } } String decUri = writer.getNamespaceContext().getNamespaceURI(prefix); boolean declareNamespace = decUri == null || !decUri.equals(nameSpace); if (nameSpace == null || nameSpace.length() == 0) { writer.writeStartElement(localName); } else { writer.writeStartElement(prefix, localName, nameSpace); } NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); String name = attr.getNodeName(); String attrPrefix = ""; int prefixIndex = name.indexOf(':'); if (prefixIndex != -1) { attrPrefix = name.substring(0, prefixIndex); name = name.substring(prefixIndex + 1); } if ("xmlns".equals(attrPrefix)) { writer.writeNamespace(name, attr.getNodeValue()); if (name.equals(prefix) && attr.getNodeValue().equals(nameSpace)) { declareNamespace = false; } } else { if ("xmlns".equals(name) && "".equals(attrPrefix)) { writer.writeNamespace("", attr.getNodeValue()); if (attr.getNodeValue().equals(nameSpace)) { declareNamespace = false; } } else { writer.writeAttribute(attrPrefix, attr.getNamespaceURI(), name, attr.getNodeValue()); } } } if (declareNamespace) { if (nameSpace == null) { writer.writeNamespace(prefix, ""); } else { writer.writeNamespace(prefix, nameSpace); } } NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); writeNode(n, writer); } writer.writeEndElement(); }
From source file:DOMTreeTest.java
public static JPanel elementPanel(Element e) { JPanel panel = new JPanel(); panel.add(new JLabel("Element: " + e.getTagName())); final NamedNodeMap map = e.getAttributes(); panel.add(new JTable(new AbstractTableModel() { public int getRowCount() { return map.getLength(); }/*from www . ja va 2 s . co m*/ public int getColumnCount() { return 2; } public Object getValueAt(int r, int c) { return c == 0 ? map.item(r).getNodeName() : map.item(r).getNodeValue(); } })); return panel; }