Java : Comment (XML) with Examples
Comment (Java SE 22 & JDK 22) with Examples.
You will find code examples on most Comment methods.
Summary
This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting '<!--' and ending '-->'. Note that this is the definition of a comment in XML, and, in practice, HTML, although some HTML tools may implement the full SGML comment structure.
final var xml = """
<root>aaa<!--XYZ-->bbb</root>
""";
final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
final var root = document.getDocumentElement();
System.out.println(root); // [root: null]
final var nodes = root.getChildNodes();
System.out.println("-- nodes --");
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i));
}
// Result
// ↓
//-- nodes --
//[#text: aaa]
//[#comment: XYZ]
//[#text: bbb]
final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();
final var root = document.createElement("root");
System.out.println(root); // [root: null]
document.appendChild(root);
final var comment = document.createComment("abcd");
System.out.println(comment); // [#comment: abcd]
System.out.println(comment.getData()); // abcd
root.appendChild(comment);
final var transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);
//<root><!--abcd--></root>
System.out.println(result.getWriter());
Fields declared in Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_PRECEDING, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Please see the link below.
Methods declared in CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Please see the link below.
Methods declared in Node
appendChild, cloneNode, compareDocumentPosition, getAttributes, getBaseURI, getChildNodes, getFeature, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, getTextContent, getUserData, hasAttributes, hasChildNodes, insertBefore, isDefaultNamespace, isEqualNode, isSameNode, isSupported, lookupNamespaceURI, lookupPrefix, normalize, removeChild, replaceChild, setNodeValue, setPrefix, setTextContent, setUserData
Please see the link below.