Java : Comment (XML) 示例

Comment (Java SE 22 & JDK 22) 示例。
您将在大多数 Comment 方法中找到代码示例。

注解 :

  • 本文可能使用了翻译软件以方便阅读。 另请查看英文原文

简介

此接口继承自 CharacterData,表示注释的内容,即起始“<!--”和结束“-->”之间的所有字符。请注意,这是 XML 中注释的定义,实际上也是 HTML 中的注释定义,尽管某些 HTML 工具可能实现完整的 SGML 注释结构。 (机器翻译)

Class diagram

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

请参阅下面的链接。

Methods declared in CharacterData

appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData

请参阅下面的链接。

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

请参阅下面的链接。


相关文章

To top of page