List of usage examples for org.w3c.dom Node COMMENT_NODE
short COMMENT_NODE
To view the source code for org.w3c.dom Node COMMENT_NODE.
Click Source Link
Comment
. From source file:ValidateLicenseHeaders.java
/** * Get all non-comment content from the element. * // w w w . j a v a2 s .c om * @param element * @return the concatenated text/cdata content */ public static String getElementContent(Element element) { if (element == null) return null; NodeList children = element.getChildNodes(); StringBuffer result = new StringBuffer(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) { result.append(child.getNodeValue()); } else if (child.getNodeType() == Node.COMMENT_NODE) { // Ignore comment nodes } else { result.append(child.getFirstChild()); } } return result.toString().trim(); }
From source file:Main.java
private static void renderNode(StringBuffer sb, Node node, String margin, String indent, String lab, String rab, String nl) {/*from ww w . java 2s .c om*/ 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:com.gargoylesoftware.htmlunit.xml.XmlUtil.java
/** * Copy all children from 'source' to 'dest', within the context of the specified page. * @param page the page which the nodes belong to * @param source the node to copy from//from w ww .j a v a 2 s .c o m * @param dest the node to copy to * @param handleXHTMLAsHTML if true elements from the XHTML namespace are handled as HTML elements instead of * DOM elements */ private static void copy(final SgmlPage page, final Node source, final DomNode dest, final boolean handleXHTMLAsHTML) { final NodeList nodeChildren = source.getChildNodes(); for (int i = 0; i < nodeChildren.getLength(); i++) { final Node child = nodeChildren.item(i); switch (child.getNodeType()) { case Node.ELEMENT_NODE: final DomNode childXml = createFrom(page, child, handleXHTMLAsHTML); dest.appendChild(childXml); copy(page, child, childXml, handleXHTMLAsHTML); break; case Node.TEXT_NODE: dest.appendChild(new DomText(page, child.getNodeValue())); break; case Node.CDATA_SECTION_NODE: dest.appendChild(new DomCDataSection(page, child.getNodeValue())); break; case Node.COMMENT_NODE: dest.appendChild(new DomComment(page, child.getNodeValue())); break; case Node.PROCESSING_INSTRUCTION_NODE: dest.appendChild(new DomProcessingInstruction(page, child.getNodeName(), child.getNodeValue())); break; default: LOG.warn( "NodeType " + child.getNodeType() + " (" + child.getNodeName() + ") is not yet supported."); } } }
From source file:DOMWriter.java
/** Writes the specified node, recursively. */ public void write(Node node) { // is there anything to do? if (node == null) { return;//ww w . j a v a2s. c o m } short type = node.getNodeType(); switch (type) { case Node.DOCUMENT_NODE: { Document document = (Document) node; fXML11 = "1.1".equals(getVersion(document)); if (!fCanonical) { if (fXML11) { fOut.println("<?xml version=\"1.1\" encoding=\"UTF-8\"?>"); } else { fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); } fOut.flush(); write(document.getDoctype()); } write(document.getDocumentElement()); break; } case Node.DOCUMENT_TYPE_NODE: { DocumentType doctype = (DocumentType) node; fOut.print("<!DOCTYPE "); fOut.print(doctype.getName()); String publicId = doctype.getPublicId(); String systemId = doctype.getSystemId(); if (publicId != null) { fOut.print(" PUBLIC '"); fOut.print(publicId); fOut.print("' '"); fOut.print(systemId); fOut.print('\''); } else if (systemId != null) { fOut.print(" SYSTEM '"); fOut.print(systemId); fOut.print('\''); } String internalSubset = doctype.getInternalSubset(); if (internalSubset != null) { fOut.println(" ["); fOut.print(internalSubset); fOut.print(']'); } fOut.println('>'); break; } case Node.ELEMENT_NODE: { fOut.print('<'); fOut.print(node.getNodeName()); Attr attrs[] = sortAttributes(node.getAttributes()); for (int i = 0; i < attrs.length; i++) { Attr attr = attrs[i]; fOut.print(' '); fOut.print(attr.getNodeName()); fOut.print("=\""); normalizeAndPrint(attr.getNodeValue(), true); fOut.print('"'); } fOut.print('>'); fOut.flush(); Node child = node.getFirstChild(); while (child != null) { write(child); child = child.getNextSibling(); } break; } case Node.ENTITY_REFERENCE_NODE: { if (fCanonical) { Node child = node.getFirstChild(); while (child != null) { write(child); child = child.getNextSibling(); } } else { fOut.print('&'); fOut.print(node.getNodeName()); fOut.print(';'); fOut.flush(); } break; } case Node.CDATA_SECTION_NODE: { if (fCanonical) { normalizeAndPrint(node.getNodeValue(), false); } else { fOut.print("<![CDATA["); fOut.print(node.getNodeValue()); fOut.print("]]>"); } fOut.flush(); break; } case Node.TEXT_NODE: { normalizeAndPrint(node.getNodeValue(), false); fOut.flush(); break; } case Node.PROCESSING_INSTRUCTION_NODE: { fOut.print("<?"); fOut.print(node.getNodeName()); String data = node.getNodeValue(); if (data != null && data.length() > 0) { fOut.print(' '); fOut.print(data); } fOut.print("?>"); fOut.flush(); break; } case Node.COMMENT_NODE: { if (!fCanonical) { fOut.print("<!--"); String comment = node.getNodeValue(); if (comment != null && comment.length() > 0) { fOut.print(comment); } fOut.print("-->"); fOut.flush(); } } } if (type == Node.ELEMENT_NODE) { fOut.print("</"); fOut.print(node.getNodeName()); fOut.print('>'); fOut.flush(); } }
From source file:com.wfreitas.camelsoap.SoapClient.java
private Comment getCommentBefore(Element element) { Node sibling = element.getPreviousSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.COMMENT_NODE) { return (Comment) sibling; } else if (sibling.getNodeType() == Node.TEXT_NODE) { // continue... sibling = sibling.getPreviousSibling(); } else {/* w ww . j a va2s . com*/ // It's an Element, CData, PI etc return null; } } return null; }
From source file:edu.cornell.mannlib.vitro.utilities.containerneutral.CheckContainerNeutrality.java
/** * Dump the first 20 nodes of an XML context, excluding comments and blank * text nodes.// w ww . j a va 2 s.co m */ @SuppressWarnings("unused") private int dumpXml(Node xmlNode, int... parms) { int remaining = (parms.length == 0) ? 20 : parms[0]; int level = (parms.length < 2) ? 1 : parms[1]; Node n = xmlNode; if (Node.COMMENT_NODE == n.getNodeType()) { return 0; } if (Node.TEXT_NODE == n.getNodeType()) { if (StringUtils.isBlank(n.getTextContent())) { return 0; } } int used = 1; System.out.println(StringUtils.repeat("-->", level) + n); NodeList nl = n.getChildNodes(); for (int i = 0; (i < nl.getLength() && remaining > used); i++) { used += dumpXml(nl.item(i), remaining - used, level + 1); } return used; }
From source file:DOMWriter.java
private void printInternal(Node node, boolean indentEndMarker) { // is there anything to do? if (node == null) { return;/*from w w w . java 2 s. c o m*/ } // JBAS-2117 - Don't skip the DOCUMENT_NODE // if (node instanceof Document) node = ((Document)node).getDocumentElement(); if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) { out.print("<?xml version='1.0'"); if (charsetName != null) out.print(" encoding='" + charsetName + "'"); out.print("?>"); if (prettyprint) out.println(); wroteXMLDeclaration = true; } int type = node.getNodeType(); boolean hasChildNodes = node.getChildNodes().getLength() > 0; String nodeName = node.getNodeName(); switch (type) { // print document case Node.DOCUMENT_NODE: { NodeList children = node.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { printInternal(children.item(iChild), false); } out.flush(); break; } // print element with attributes case Node.ELEMENT_NODE: { Element element = (Element) node; if (prettyprint) { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } prettyIndent++; } out.print('<'); out.print(nodeName); Map nsMap = new HashMap(); String elPrefix = node.getPrefix(); String elNamespaceURI = node.getNamespaceURI(); if (elPrefix != null) { String nsURI = getNamespaceURI(elPrefix, element, rootNode); nsMap.put(elPrefix, nsURI); } Attr attrs[] = sortAttributes(node.getAttributes()); for (int i = 0; i < attrs.length; i++) { Attr attr = attrs[i]; String atPrefix = attr.getPrefix(); String atName = attr.getNodeName(); String atValue = normalize(attr.getNodeValue(), canonical); if (atName.equals("xmlns")) currentDefaultNamespace = atValue; if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) { String nsURI = getNamespaceURI(atPrefix, element, rootNode); nsMap.put(atPrefix, nsURI); // xsi:type='ns1:SubType', xsi:type='xsd:string' if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) { // xsi defined on the envelope if (nsURI == null) nsURI = getNamespaceURI(atPrefix, element, null); if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) { String typePrefix = atValue.substring(0, atValue.indexOf(":")); String typeURI = getNamespaceURI(typePrefix, element, rootNode); nsMap.put(typePrefix, typeURI); } } } out.print(" " + atName + "='" + atValue + "'"); } // Add namespace declaration for prefixes // that are defined further up the tree if (completeNamespaces) { Iterator itPrefix = nsMap.keySet().iterator(); while (itPrefix.hasNext()) { String prefix = (String) itPrefix.next(); String nsURI = (String) nsMap.get(prefix); if (nsURI == null) { nsURI = getNamespaceURI(prefix, element, null); out.print(" xmlns:" + prefix + "='" + nsURI + "'"); } } } // The SAX ContentHandler will by default not add the namespace declaration // <Hello xmlns='http://somens'>World</Hello> if (elPrefix == null && elNamespaceURI != null) { String defaultNamespace = element.getAttribute("xmlns"); if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) { out.print(" xmlns='" + elNamespaceURI + "'"); currentDefaultNamespace = elNamespaceURI; } } if (hasChildNodes) { out.print('>'); } // Find out if the end marker is indented indentEndMarker = isEndMarkerIndented(node); if (indentEndMarker) { out.print('\n'); } NodeList childNodes = node.getChildNodes(); int len = childNodes.getLength(); for (int i = 0; i < len; i++) { Node childNode = childNodes.item(i); printInternal(childNode, false); } break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { if (canonical) { NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { printInternal(children.item(i), false); } } } else { out.print('&'); out.print(nodeName); out.print(';'); } break; } // print cdata sections case Node.CDATA_SECTION_NODE: { if (canonical) { out.print(normalize(node.getNodeValue(), canonical)); } else { out.print("<![CDATA["); out.print(node.getNodeValue()); out.print("]]>"); } break; } // print text case Node.TEXT_NODE: { String text = normalize(node.getNodeValue(), canonical); if (text.trim().length() > 0) { out.print(text); } else if (prettyprint == false && ignoreWhitespace == false) { out.print(text); } break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { out.print("<?"); out.print(nodeName); String data = node.getNodeValue(); if (data != null && data.length() > 0) { out.print(' '); out.print(data); } out.print("?>"); break; } // print comment case Node.COMMENT_NODE: { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } out.print("<!--"); String data = node.getNodeValue(); if (data != null) { out.print(data); } out.print("-->"); if (prettyprint) { out.print('\n'); } break; } } if (type == Node.ELEMENT_NODE) { if (prettyprint) prettyIndent--; if (hasChildNodes == false) { out.print("/>"); } else { if (indentEndMarker) { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } } out.print("</"); out.print(nodeName); out.print('>'); } if (prettyIndent > 0) { out.print('\n'); } } out.flush(); }
From source file:DOMWriter.java
private void printInternal(Node node, boolean indentEndMarker) { // is there anything to do? if (node == null) { return;/*from w ww . ja v a 2 s . c o m*/ } // JBAS-2117 - Don't skip the DOCUMENT_NODE // if (node instanceof Document) node = // ((Document)node).getDocumentElement(); if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) { out.print("<?xml version='1.0'"); if (charsetName != null) out.print(" encoding='" + charsetName + "'"); out.print("?>"); if (prettyprint) out.println(); wroteXMLDeclaration = true; } int type = node.getNodeType(); boolean hasChildNodes = node.getChildNodes().getLength() > 0; String nodeName = node.getNodeName(); switch (type) { // print document case Node.DOCUMENT_NODE: { NodeList children = node.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { printInternal(children.item(iChild), false); } out.flush(); break; } // print element with attributes case Node.ELEMENT_NODE: { Element element = (Element) node; if (prettyprint) { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } prettyIndent++; } out.print('<'); out.print(nodeName); Map nsMap = new HashMap(); String elPrefix = node.getPrefix(); String elNamespaceURI = node.getNamespaceURI(); if (elPrefix != null) { String nsURI = getNamespaceURI(elPrefix, element, rootNode); nsMap.put(elPrefix, nsURI); } Attr attrs[] = sortAttributes(node.getAttributes()); for (int i = 0; i < attrs.length; i++) { Attr attr = attrs[i]; String atPrefix = attr.getPrefix(); String atName = attr.getNodeName(); String atValue = normalize(attr.getNodeValue(), canonical); if (atName.equals("xmlns")) currentDefaultNamespace = atValue; if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) { String nsURI = getNamespaceURI(atPrefix, element, rootNode); nsMap.put(atPrefix, nsURI); // xsi:type='ns1:SubType', xsi:type='xsd:string' if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) { // xsi defined on the envelope if (nsURI == null) nsURI = getNamespaceURI(atPrefix, element, null); if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) { String typePrefix = atValue.substring(0, atValue.indexOf(":")); String typeURI = getNamespaceURI(typePrefix, element, rootNode); nsMap.put(typePrefix, typeURI); } } } out.print(" " + atName + "='" + atValue + "'"); } // Add namespace declaration for prefixes // that are defined further up the tree if (completeNamespaces) { Iterator itPrefix = nsMap.keySet().iterator(); while (itPrefix.hasNext()) { String prefix = (String) itPrefix.next(); String nsURI = (String) nsMap.get(prefix); if (nsURI == null) { nsURI = getNamespaceURI(prefix, element, null); out.print(" xmlns:" + prefix + "='" + nsURI + "'"); } } } // The SAX ContentHandler will by default not add the namespace // declaration // <Hello xmlns='http://somens'>World</Hello> if (elPrefix == null && elNamespaceURI != null) { String defaultNamespace = element.getAttribute("xmlns"); if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) { out.print(" xmlns='" + elNamespaceURI + "'"); currentDefaultNamespace = elNamespaceURI; } } if (hasChildNodes) { out.print('>'); } // Find out if the end marker is indented indentEndMarker = isEndMarkerIndented(node); if (indentEndMarker) { out.print('\n'); } NodeList childNodes = node.getChildNodes(); int len = childNodes.getLength(); for (int i = 0; i < len; i++) { Node childNode = childNodes.item(i); printInternal(childNode, false); } break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { if (canonical) { NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { printInternal(children.item(i), false); } } } else { out.print('&'); out.print(nodeName); out.print(';'); } break; } // print cdata sections case Node.CDATA_SECTION_NODE: { if (canonical) { out.print(normalize(node.getNodeValue(), canonical)); } else { out.print("<![CDATA["); out.print(node.getNodeValue()); out.print("]]>"); } break; } // print text case Node.TEXT_NODE: { String text = normalize(node.getNodeValue(), canonical); if (text.trim().length() > 0) { out.print(text); } else if (prettyprint == false && ignoreWhitespace == false) { out.print(text); } break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { out.print("<?"); out.print(nodeName); String data = node.getNodeValue(); if (data != null && data.length() > 0) { out.print(' '); out.print(data); } out.print("?>"); break; } // print comment case Node.COMMENT_NODE: { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } out.print("<!--"); String data = node.getNodeValue(); if (data != null) { out.print(data); } out.print("-->"); if (prettyprint) { out.print('\n'); } break; } } if (type == Node.ELEMENT_NODE) { if (prettyprint) prettyIndent--; if (hasChildNodes == false) { out.print("/>"); } else { if (indentEndMarker) { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } } out.print("</"); out.print(nodeName); out.print('>'); } if (prettyIndent > 0) { out.print('\n'); } } out.flush(); }
From source file:com.mediaworx.xmlutils.XmlHelper.java
/** * Removes text nodes that are empty or contain whitespace only if the parent node has at least one child of any * of the following types: ELEMENT, CDATA, COMMENT. This is used to improve the XML format when using a transformer * to do the formatting (whitespace nodes are interfering with indentation and line breaks). * This method was modeled after a method by "user2401669" found on * <a href="http://stackoverflow.com/questions/16641835/strange-xml-indentation">StackOverflow</a>. *///from ww w.j a v a2 s . c o m public static void cleanEmptyTextNodes(Node parentNode) { boolean removeEmptyTextNodes = false; Node childNode = parentNode.getFirstChild(); while (childNode != null) { short nodeType = childNode.getNodeType(); if (nodeType == Node.ELEMENT_NODE || nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.COMMENT_NODE) { removeEmptyTextNodes = true; if (nodeType == Node.ELEMENT_NODE) { cleanEmptyTextNodes(childNode); // recurse into subtree } } childNode = childNode.getNextSibling(); } if (removeEmptyTextNodes) { removeEmptyTextNodes(parentNode); } }
From source file:mondrian.test.DiffRepository.java
private static void writeNode(Node node, XMLOutput out) { final NodeList childNodes; switch (node.getNodeType()) { case Node.DOCUMENT_NODE: out.print("<?xml version=\"1.0\" ?>" + Util.nl); childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); writeNode(child, out);/*from ww w. ja v a 2s .com*/ } // writeNode(((Document) node).getDocumentElement(), out); break; case Node.ELEMENT_NODE: Element element = (Element) node; final String tagName = element.getTagName(); out.beginBeginTag(tagName); // Attributes. final NamedNodeMap attributeMap = element.getAttributes(); for (int i = 0; i < attributeMap.getLength(); i++) { final Node att = attributeMap.item(i); out.attribute(att.getNodeName(), att.getNodeValue()); } out.endBeginTag(tagName); // Write child nodes, ignoring attributes but including text. childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ATTRIBUTE_NODE) { continue; } writeNode(child, out); } out.endTag(tagName); break; case Node.ATTRIBUTE_NODE: out.attribute(node.getNodeName(), node.getNodeValue()); break; case Node.CDATA_SECTION_NODE: CDATASection cdata = (CDATASection) node; out.cdata(cdata.getNodeValue(), true); break; case Node.TEXT_NODE: Text text = (Text) node; final String wholeText = text.getNodeValue(); if (!isWhitespace(wholeText)) { out.cdata(wholeText, false); } break; case Node.COMMENT_NODE: Comment comment = (Comment) node; out.print("<!--" + comment.getNodeValue() + "-->" + Util.nl); break; default: throw new RuntimeException("unexpected node type: " + node.getNodeType() + " (" + node + ")"); } }