Java : Comment (XML) con ejemplos
Comment (Java SE 22 & JDK 22) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de Comment.
Nota :
- Este artículo puede utilizar software de traducción para su comodidad. Consulte también la versión original en inglés.
Summary
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
Consulte el siguiente enlace.
Methods declared in CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Consulte el siguiente enlace.
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
Consulte el siguiente enlace.