Java : Node (XML) 示例

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

注解 :

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

简介

Node 接口是整个文档对象模型的主要数据类型。它表示文档树中的单个节点。 (机器翻译)

Class diagram

Code examples on this page use the printDocument method below.

public void printDocument(Document document) throws TransformerException {
    final var transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.print(result.getWriter());
}
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 child = document.createElement("child");
System.out.println(child); // [child: null]

root.appendChild(child);

final var text = document.createTextNode("abcd");
System.out.println(text); // [#text: abcd]

child.appendChild(text);

//<root>
//    <child>abcd</child>
//</root>
printDocument(document);

Fields

static final short ATTRIBUTE_NODE

该节点是一个 Attr。 (机器翻译)

final var xml = """
        <root attr="abc"/>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node attr = document.getDocumentElement().getAttributes().getNamedItem("attr");
System.out.println(attr); // attr="abc"

System.out.println(Node.ATTRIBUTE_NODE); // 2
System.out.println(attr.getNodeType() == Node.ATTRIBUTE_NODE); // true

static final short CDATA_SECTION_NODE

该节点是一个 CDATASection。 (机器翻译)

final var xml = """
        <root><![CDATA[<&>]]></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node cdata = document.getDocumentElement().getFirstChild();
System.out.println(cdata); // [#cdata-section: <&>]

System.out.println(Node.CDATA_SECTION_NODE); // 4
System.out.println(cdata.getNodeType() == Node.CDATA_SECTION_NODE); // true

static final short COMMENT_NODE

该节点是一个评论。 (机器翻译)

final var xml = """
        <root><!-- abc --></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node comment = document.getDocumentElement().getFirstChild();
System.out.println(comment); // [#comment:  abc ]

System.out.println(Node.COMMENT_NODE); // 8
System.out.println(comment.getNodeType() == Node.COMMENT_NODE); // true

static final short DOCUMENT_FRAGMENT_NODE

该节点是一个 DocumentFragment。 (机器翻译)

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final Node fragment = document.createDocumentFragment();
System.out.println(fragment); // [#document-fragment: null]

System.out.println(Node.DOCUMENT_FRAGMENT_NODE); // 11
System.out.println(fragment.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE); // true

static final short DOCUMENT_NODE

该节点是一个文档。 (机器翻译)

final var xml = """
        <root/>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final Node document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
System.out.println(document); // [#document: null]

System.out.println(Node.DOCUMENT_NODE); // 9
System.out.println(document.getNodeType() == Node.DOCUMENT_NODE); // true

static final short DOCUMENT_POSITION_CONTAINED_BY

该节点包含在引用节点中。 (机器翻译)

final var xml = """
        <root><child/></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 child = root.getFirstChild();
System.out.println(child); // [child: null]

final var type = root.compareDocumentPosition(child);

System.out.printf("%#x%n", type); // 0x14
System.out.printf("%#x%n", Node.DOCUMENT_POSITION_CONTAINED_BY); // 0x10
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_CONTAINED_BY); // 0x10

static final short DOCUMENT_POSITION_CONTAINS

该节点包含参考节点。 (机器翻译)

final var xml = """
        <root><child/></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 child = root.getFirstChild();
System.out.println(child); // [child: null]

final var type = child.compareDocumentPosition(root);

System.out.printf("%#x%n", type); // 0xa
System.out.printf("%#x%n", Node.DOCUMENT_POSITION_CONTAINS); // 0x8
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_CONTAINS); // 0x8

static final short DOCUMENT_POSITION_DISCONNECTED

两个节点已断开连接。 (机器翻译)

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

final var document1 = builder.newDocument();
final var node1 = document1.createTextNode("abcd");
System.out.println(node1); // [#text: abcd]

final var document2 = builder.newDocument();
final var node2 = document2.createTextNode("xyz");
System.out.println(node2); // [#text: xyz]

final var type = node1.compareDocumentPosition(node2);

System.out.printf("%#x%n", type); // 0x23
System.out.printf("%#x%n", Node.DOCUMENT_POSITION_DISCONNECTED); // 0x1
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_DISCONNECTED); // 0x1

static final short DOCUMENT_POSITION_FOLLOWING

该节点跟随参考节点。 (机器翻译)

final var xml = """
        <root>
            <child-a/>
            <child-b/>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]

final var childB = document.getElementsByTagName("child-b").item(0);
System.out.println(childB); // [child-b: null]

final var type = childA.compareDocumentPosition(childB);

System.out.printf("%#x%n", type); // 0x4
System.out.printf("%#x%n", Node.DOCUMENT_POSITION_FOLLOWING); // 0x4
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_FOLLOWING); // 0x4

static final short DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC

确定在前还是在后取决于具体实施。 (机器翻译)

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

final var document1 = builder.newDocument();
final var node1 = document1.createTextNode("abcd");
System.out.println(node1); // [#text: abcd]

final var document2 = builder.newDocument();
final var node2 = document2.createTextNode("xyz");
System.out.println(node2); // [#text: xyz]

final short type = node1.compareDocumentPosition(node2);

System.out.printf("%#x%n", type); // 0x23
System.out.printf("%#x%n", Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC); // 0x20
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC); // 0x20

static final short DOCUMENT_POSITION_PRECEDING

第二个节点位于参考节点之前。 (机器翻译)

final var xml = """
        <root>
            <child-a/>
            <child-b/>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]

final var childB = document.getElementsByTagName("child-b").item(0);
System.out.println(childB); // [child-b: null]

final var type = childB.compareDocumentPosition(childA);

System.out.printf("%#x%n", type); // 0x2
System.out.printf("%#x%n", Node.DOCUMENT_POSITION_PRECEDING); // 0x2
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_PRECEDING); // 0x2

static final short DOCUMENT_TYPE_NODE

该节点是一个 DocumentType。 (机器翻译)

final var xml = """
        <!DOCTYPE root>
        <root/>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node doctype = document.getDoctype();
System.out.println(doctype); // [root: null]

System.out.println(Node.DOCUMENT_TYPE_NODE); // 10
System.out.println(doctype.getNodeType() == Node.DOCUMENT_TYPE_NODE); // true

static final short ELEMENT_NODE

该节点是一个元素。 (机器翻译)

final var xml = """
        <root/>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node element = document.getDocumentElement();
System.out.println(element); // [root: null]

System.out.println(Node.ELEMENT_NODE); // 1
System.out.println(element.getNodeType() == Node.ELEMENT_NODE); // true

static final short ENTITY_NODE

该节点是一个实体。 (机器翻译)

final var xml = """
        <!DOCTYPE root [
            <!ENTITY aaa "bbb">
        ]>
        <root>&aaa;</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node entity = document.getDoctype().getEntities().item(0);
System.out.println(entity); // [aaa: null]

System.out.println(Node.ENTITY_NODE); // 6
System.out.println(entity.getNodeType() == Node.ENTITY_NODE); // true

//<root>bbb</root>
printDocument(document);

static final short ENTITY_REFERENCE_NODE

该节点是一个 EntityReference。 (机器翻译)

final var xml = """
        <!DOCTYPE root [
            <!ENTITY aaa "bbb">
        ]>
        <root>&aaa;</root>
        """;

final var factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);

final var document = factory.newDocumentBuilder().parse(
        new ByteArrayInputStream(xml.getBytes()));

final Node entityReference = document.getDocumentElement().getFirstChild();
System.out.println(entityReference); // [aaa: null]

System.out.println(Node.ENTITY_REFERENCE_NODE); // 5
System.out.println(entityReference.getNodeType() == Node.ENTITY_REFERENCE_NODE); // true

static final short NOTATION_NODE

节点是一种符号。 (机器翻译)

final var xml = """
        <!DOCTYPE root [
           <!NOTATION sample SYSTEM "aaa">
        ]>
        <root/>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node notation = document.getDoctype().getNotations().item(0);
System.out.println(notation); // [sample: null]

System.out.println(Node.NOTATION_NODE); // 12
System.out.println(notation.getNodeType() == Node.NOTATION_NODE); // true

static final short PROCESSING_INSTRUCTION_NODE

该节点是一个 ProcessingInstruction。 (机器翻译)

final var xml = """
        <root><?target content?></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node pi = document.getDocumentElement().getFirstChild();
System.out.println(pi); // [target: content]

System.out.println(Node.PROCESSING_INSTRUCTION_NODE); // 7
System.out.println(pi.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE); // true

static final short TEXT_NODE

该节点是一个文本节点。 (机器翻译)

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node text = document.getDocumentElement().getFirstChild();
System.out.println(text); // [#text: abcd]

System.out.println(Node.TEXT_NODE); // 3
System.out.println(text.getNodeType() == Node.TEXT_NODE); // true

Methods

Node appendChild (Node newChild)

将节点 newChild 添加到此节点的子节点列表的末尾。 (机器翻译)

final var xml = """
        <root/>
        """;

final var document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node child = document.createElement("child");
System.out.println(child); // [child: null]

final Node ret = root.appendChild(child);
System.out.println(ret); // [child: null]

//<root>
//    <child/>
//</root>
printDocument(document);

Node cloneNode (boolean deep)

返回此节点的副本,即作为节点的通用复制构造函数。 (机器翻译)

final var xml = """
        <root><a><b>xyz</b></a></root>
        """;

final var document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <a>
//        <b>xyz</b>
//    </a>
//</root>
printDocument(document);

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node childA = document.getElementsByTagName("a").item(0);
System.out.println(childA); // [a: null]

final Node clonedDeepNode = childA.cloneNode(true);
final Node clonedNode = childA.cloneNode(false);

root.appendChild(clonedDeepNode);
root.appendChild(clonedNode);

//<root>
//    <a>
//        <b>xyz</b>
//    </a>
//    <a>
//        <b>xyz</b>
//    </a>
//    <a/>
//</root>
printDocument(document);

short compareDocumentPosition (Node other)

将参考节点(即调用此方法的节点)与节点(即作为参数传递的节点)进行比较,比较它们在文档中的位置和文档顺序。 (机器翻译)

final var xml = """
        <root>
            <child/>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]

final short type = root.compareDocumentPosition(child);
System.out.printf("%#x%n", type); // 0x14

System.out.printf("%#x%n", Node.DOCUMENT_POSITION_CONTAINED_BY); // 0x10
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_CONTAINED_BY); // 0x10

System.out.printf("%#x%n", Node.DOCUMENT_POSITION_FOLLOWING); // 0x4
System.out.printf("%#x%n", type & Node.DOCUMENT_POSITION_FOLLOWING); // 0x4

NamedNodeMap getAttributes ()

包含此节点的属性的 NamedNodeMap(如果它是一个元素)或否则为 null。 (机器翻译)

final var xml = """
        <root>
            <child aa="AA" bb="BB" />
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]

final var attributes = child.getAttributes();

System.out.println("-- attributes --");
for (int i = 0; i < attributes.getLength(); i++) {
    final var attr = attributes.item(i);
    System.out.println(attr);
}

// Result
// ↓
//-- attributes --
//aa="AA"
//bb="BB"

String getBaseURI ()

此节点的绝对基 URI;如果实现无法获取绝对 URI,则为 null。 (机器翻译)

final var path = Path.of("R:", "java-work", "a.xml");
System.out.println(path); // R:\java-work\a.xml

Files.writeString(path, """
        <root>
            <child/>
        </root>
        """);

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(path.toFile());

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]
System.out.println(root.getBaseURI()); // file:/R:/java-work/a.xml

NodeList getChildNodes ()

包含此节点的所有子节点的 NodeList。 (机器翻译)

final var xml = """
        <root><child-a/><child-b/></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final var nodes = root.getChildNodes();
System.out.println(nodes.getLength()); // 2

System.out.println("-- nodes --");
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i));
}

// Result
// ↓
//-- nodes --
//[child-a: null]
//[child-b: null]
final var xml = """
        <root>
            <child-a/>
            <child-b/>
            <!-- comment! -->
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final var nodes = root.getChildNodes();
System.out.println(nodes.getLength()); // 7

System.out.println("-- nodes --");
for (int i = 0; i < nodes.getLength(); i++) {
    final var node = nodes.item(i);
    if (node instanceof Text text) {
        // For readability, line separators are converted to "\n" and spaces to "*".
        final var data = text.getData().replace("\n", "\\n").replace(" ", "*");
        System.out.println("[#text: " + data + "]");
    } else {
        System.out.println(node);
    }
}

// Result
// ↓
//-- nodes --
//[#text: \n****]
//[child-a: null]
//[#text: \n****]
//[child-b: null]
//[#text: \n****]
//[#comment:  comment! ]
//[#text: \n]

Object getFeature (String feature, String version)

此方法返回一个专门的对象,该对象实现指定功能和版本的专门 API,如中所述。 (机器翻译)

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

System.out.println(root.isSupported("XML", "3.0")); // true
System.out.println(root.getFeature("XML", "3.0")); // [root: null]

System.out.println(root.isSupported("XML", "4.0")); // false
System.out.println(root.getFeature("XML", "4.0")); // null

Node getFirstChild ()

此节点的第一个子节点。 (机器翻译)

final var xml = """
        <root><child-a/><child-b/><child-c/></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child-a/>
//    <child-b/>
//    <child-c/>
//</root>
printDocument(document);

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node firstChild = root.getFirstChild();
System.out.println(firstChild); // [child-a: null]

final Node lastChild = root.getLastChild();
System.out.println(lastChild); // [child-c: null]

Node getLastChild ()

此节点的最后一个子节点。 (机器翻译)

final var xml = """
        <root><child-a/><child-b/><child-c/></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child-a/>
//    <child-b/>
//    <child-c/>
//</root>
printDocument(document);

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node firstChild = root.getFirstChild();
System.out.println(firstChild); // [child-a: null]

final Node lastChild = root.getLastChild();
System.out.println(lastChild); // [child-c: null]

String getLocalName ()

返回此节点的限定名称的本地部分。 (机器翻译)

final var xml = """
        <ns:root xmlns:ns="sample">
            <ns:child/>
        </ns:root>
        """;

final var builder = DocumentBuilderFactory.newNSInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node child = document.getElementsByTagName("ns:child").item(0);
System.out.println(child); // [ns:child: null]

System.out.println(child.getPrefix()); // ns
System.out.println(child.getLocalName()); // child
System.out.println(child.getNamespaceURI()); // sample

String getNamespaceURI ()

此节点的命名空间 URI,如果未指定则为 null(请参阅)。 (机器翻译)

final var xml = """
        <ns:root xmlns:ns="sample">
            <ns:child/>
        </ns:root>
        """;

final var builder = DocumentBuilderFactory.newNSInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node child = document.getElementsByTagName("ns:child").item(0);
System.out.println(child); // [ns:child: null]

System.out.println(child.getPrefix()); // ns
System.out.println(child.getLocalName()); // child
System.out.println(child.getNamespaceURI()); // sample

Node getNextSibling ()

紧接此节点之后的节点。 (机器翻译)

final var xml = """
        <root><child-a/><child-b/></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child-a/>
//    <child-b/>
//</root>
printDocument(document);

final Node childA = document.getDocumentElement().getFirstChild();
System.out.println(childA); // [child-a: null]

final Node childB = childA.getNextSibling();
System.out.println(childB); // [child-b: null]

final Node childC = childB.getNextSibling();
System.out.println(childC); // null

String getNodeName ()

此节点的名称取决于其类型;参见上表。 (机器翻译)

final var xml = """
        <root>
            <child aa="AA">abcd</child>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

// Element
final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child.getNodeType() == Node.ELEMENT_NODE); // true
System.out.println(child.getNodeName()); // child
System.out.println(child.getNodeValue()); // null

// Attr
final Node attr = child.getAttributes().item(0);
System.out.println(attr.getNodeType() == Node.ATTRIBUTE_NODE); // true
System.out.println(attr.getNodeName()); // aa
System.out.println(attr.getNodeValue()); // AA

// Text
final Node text = child.getFirstChild();
System.out.println(text.getNodeType() == Node.TEXT_NODE); // true
System.out.println(text.getNodeName()); // #text
System.out.println(text.getNodeValue()); // abcd

short getNodeType ()

表示底层对象类型的代码,如上所述。 (机器翻译)

final var xml = """
        <root>
            <child aa="AA">abcd</child>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

// Element
final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child.getNodeType() == Node.ELEMENT_NODE); // true
System.out.println(child.getNodeName()); // child
System.out.println(child.getNodeValue()); // null

// Attr
final Node attr = child.getAttributes().item(0);
System.out.println(attr.getNodeType() == Node.ATTRIBUTE_NODE); // true
System.out.println(attr.getNodeName()); // aa
System.out.println(attr.getNodeValue()); // AA

// Text
final Node text = child.getFirstChild();
System.out.println(text.getNodeType() == Node.TEXT_NODE); // true
System.out.println(text.getNodeName()); // #text
System.out.println(text.getNodeValue()); // abcd

String getNodeValue ()

此节点的值取决于其类型;参见上表。 (机器翻译)

final var xml = """
        <root>
            <child aa="AA">abcd</child>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

// Element
final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child.getNodeType() == Node.ELEMENT_NODE); // true
System.out.println(child.getNodeName()); // child
System.out.println(child.getNodeValue()); // null

// Attr
final Node attr = child.getAttributes().item(0);
System.out.println(attr.getNodeType() == Node.ATTRIBUTE_NODE); // true
System.out.println(attr.getNodeName()); // aa
System.out.println(attr.getNodeValue()); // AA

// Text
final Node text = child.getFirstChild();
System.out.println(text.getNodeType() == Node.TEXT_NODE); // true
System.out.println(text.getNodeName()); // #text
System.out.println(text.getNodeValue()); // abcd

Document getOwnerDocument ()

与此节点关联的 Document 对象。 (机器翻译)

final var xml = """
        <root>
            <child/>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]

final var ownerDocument = child.getOwnerDocument();
System.out.println(document.isSameNode(ownerDocument)); // true

Node getParentNode ()

此节点的父节点。 (机器翻译)

final var xml = """
        <root>
            <child>
                <child-child/>
            </child>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node childChild = document.getElementsByTagName("child-child").item(0);
System.out.println(childChild); // [child-child: null]

final Node child = childChild.getParentNode();
System.out.println(child); // [child: null]

final Node root = child.getParentNode();
System.out.println(root); // [root: null]

String getPrefix ()

此节点的命名空间前缀,如果未指定,则为 null。 (机器翻译)

final var xml = """
        <ns:root xmlns:ns="sample">
            <ns:child/>
        </ns:root>
        """;

final var builder = DocumentBuilderFactory.newNSInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node child = document.getElementsByTagName("ns:child").item(0);
System.out.println(child); // [ns:child: null]

System.out.println(child.getPrefix()); // ns
System.out.println(child.getLocalName()); // child
System.out.println(child.getNamespaceURI()); // sample

Node getPreviousSibling ()

紧接此节点之前的节点。 (机器翻译)

final var xml = """
        <root><child-y/><child-z/></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child-y/>
//    <child-z/>
//</root>
printDocument(document);

final Node childZ = document.getDocumentElement().getLastChild();
System.out.println(childZ); // [child-z: null]

final Node childY = childZ.getPreviousSibling();
System.out.println(childY); // [child-y: null]

final Node childX = childY.getPreviousSibling();
System.out.println(childX); // null

String getTextContent ()

该属性返回此节点及其后代的文本内容。 (机器翻译)

final var xml = """
        <root>aaa<child>XYZ</child>bbb</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]
System.out.println(root.getTextContent()); // aaaXYZbbb

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]
System.out.println(child.getTextContent()); // XYZ

Object getUserData (String key)

检索与此节点上的键关联的对象。 (机器翻译)

final var xml = """
        <root>
            <child-a/>
            <child-b/>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]

final Node childB = document.getElementsByTagName("child-b").item(0);
System.out.println(childB); // [child-b: null]

final var handler = new UserDataHandler() {
    @Override
    public void handle(short operation, String key, Object data, Node src, Node dst) {
        System.out.println("-- UserDataHandler.handle --");
        System.out.println(
                "operation = " + operation + " : key = " + key +
                        " : data = " + data + " : src = " + src + " : dst = " + dst);
    }
};

final var retA = childA.setUserData("a-key", "aaa", handler);
System.out.println(retA); // null

final var retB = childB.setUserData("b-key", "bbb", handler);
System.out.println(retB); // null

System.out.println(childA.getUserData("a-key")); // aaa
System.out.println(childA.getUserData("b-key")); // null

System.out.println(childB.getUserData("a-key")); // null
System.out.println(childB.getUserData("b-key")); // bbb

final var clonedNode = childA.cloneNode(false);

// Result
// ↓
//-- UserDataHandler.handle --
//operation = 1 : key = a-key : data = aaa : src = [child-a: null] : dst = [child-a: null]

final var renamedNode = document.renameNode(childB, null, "child-z");

// Result
// ↓
//-- UserDataHandler.handle --
//operation = 4 : key = b-key : data = bbb : src = [child-z: null] : dst = null

boolean hasAttributes ()

返回此节点(如果它是一个元素)是否具有任何属性。 (机器翻译)

final var xml = """
        <root>
            <child-a/>
            <child-b aa="AA" />
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]
System.out.println(childA.hasAttributes()); // false

final Node childB = document.getElementsByTagName("child-b").item(0);
System.out.println(childB); // [child-b: null]
System.out.println(childB.hasAttributes()); // true

boolean hasChildNodes ()

返回此节点是否有任何子节点。 (机器翻译)

final var xml = """
        <root><child/></root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]
System.out.println(root.hasChildNodes()); // true
System.out.println(root.getChildNodes().getLength()); // 1

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]
System.out.println(child.hasChildNodes()); // false
System.out.println(child.getChildNodes().getLength()); // 0

Node insertBefore (Node newChild, Node refChild)

在现有子节点 refChild 之前插入节点 newChild。 (机器翻译)

final var xml = """
        <root><child-z/></root>
        """;

final var document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child-z/>
//</root>
printDocument(document);

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node childZ = document.getElementsByTagName("child-z").item(0);
System.out.println(childZ); // [child-z: null]

final Node childX = document.createElement("child-x");
final Node ret1 = root.insertBefore(childX, childZ);
System.out.println(ret1); // [child-x: null]

final Node childY = document.createElement("child-y");
final Node ret2 = root.insertBefore(childY, childZ);
System.out.println(ret2); // [child-y: null]

//<root>
//    <child-x/>
//    <child-y/>
//    <child-z/>
//</root>
printDocument(document);

boolean isDefaultNamespace (String namespaceURI)

此方法检查指定的 namespaceURI 是否是默认命名空间。 (机器翻译)

final var xml = """
        <root xmlns="sample1" xmlns:ns="sample2">
            <child-a/>
            <ns:child-b/>
        </root>
        """;

final var builder = DocumentBuilderFactory.newNSInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]

System.out.println(childA.getNamespaceURI()); // sample1
System.out.println(childA.isDefaultNamespace("sample1")); // true
System.out.println(childA.isDefaultNamespace("sample2")); // false

final Node childB = document.getElementsByTagName("ns:child-b").item(0);
System.out.println(childB); // [ns:child-b: null]

System.out.println(childB.getNamespaceURI()); // sample2
System.out.println(childB.isDefaultNamespace("sample1")); // true
System.out.println(childB.isDefaultNamespace("sample2")); // false

boolean isEqualNode (Node arg)

测试两个节点是否相等。 (机器翻译)

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final Node nodeA1 = document.createElement("node-a");
final Node nodeA2 = document.createElement("node-a");

final Node nodeB = document.createElement("node-b");

System.out.println(nodeA1.isEqualNode(nodeA1)); // true
System.out.println(nodeA1.isEqualNode(nodeA2)); // true
System.out.println(nodeA1.isEqualNode(nodeB)); // false

System.out.println(nodeA1.isSameNode(nodeA1)); // true
System.out.println(nodeA1.isSameNode(nodeA2)); // false
System.out.println(nodeA1.isSameNode(nodeB)); // false

boolean isSameNode (Node other)

返回此节点是否与给定节点相同。 (机器翻译)

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final Node nodeA1 = document.createElement("node-a");
final Node nodeA2 = document.createElement("node-a");

final Node nodeB = document.createElement("node-b");

System.out.println(nodeA1.isEqualNode(nodeA1)); // true
System.out.println(nodeA1.isEqualNode(nodeA2)); // true
System.out.println(nodeA1.isEqualNode(nodeB)); // false

System.out.println(nodeA1.isSameNode(nodeA1)); // true
System.out.println(nodeA1.isSameNode(nodeA2)); // false
System.out.println(nodeA1.isSameNode(nodeB)); // false

boolean isSupported (String feature, String version)

测试 DOM 实现是否实现了特定的功能以及该功能是否受此节点支持,如中所述。 (机器翻译)

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

System.out.println(root.isSupported("XML", "3.0")); // true
System.out.println(root.getFeature("XML", "3.0")); // [root: null]

System.out.println(root.isSupported("XML", "4.0")); // false
System.out.println(root.getFeature("XML", "4.0")); // null

String lookupNamespaceURI (String prefix)

从此节点开始查找与给定前缀关联的命名空间 URI。 (机器翻译)

final var xml = """
        <root xmlns:ns1="sample1">
            <ns1:child-a>
                <ns2:child-b xmlns:ns2="sample2"/>
            </ns1:child-a>
        </root>
        """;

final var builder = DocumentBuilderFactory.newNSInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node childA = document.getElementsByTagName("ns1:child-a").item(0);
System.out.println(childA); // [ns1:child-a: null]

System.out.println(childA.lookupNamespaceURI("ns1")); // sample1
System.out.println(childA.lookupNamespaceURI("ns2")); // null

final Node childB = document.getElementsByTagName("ns2:child-b").item(0);
System.out.println(childB); // [ns2:child-b: null]

System.out.println(childB.lookupNamespaceURI("ns1")); // sample1
System.out.println(childB.lookupNamespaceURI("ns2")); // sample2

String lookupPrefix (String namespaceURI)

从此节点开始查找与给定命名空间 URI 关联的前缀。 (机器翻译)

final var xml = """
        <root xmlns:ns1="sample1">
            <ns1:child-a>
                <ns2:child-b xmlns:ns2="sample2"/>
            </ns1:child-a>
        </root>
        """;

final var builder = DocumentBuilderFactory.newNSInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node childA = document.getElementsByTagName("ns1:child-a").item(0);
System.out.println(childA); // [ns1:child-a: null]

System.out.println(childA.lookupPrefix("sample1")); // ns1
System.out.println(childA.lookupPrefix("sample2")); // null

final Node childB = document.getElementsByTagName("ns2:child-b").item(0);
System.out.println(childB); // [ns2:child-b: null]

System.out.println(childB.lookupPrefix("sample1")); // ns1
System.out.println(childB.lookupPrefix("sample2")); // ns2

void normalize ()

将此节点下子树的完整深度中的所有文本节点(包括属性节点)放入“正常”形式,其中只有结构(例如,元素、注释、处理指令、CDATA 部分和实体引用)分隔文本节点,即,既没有相邻的文本节点也没有空的文本节点。 (机器翻译)

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final Node root = document.createElement("root");

// Intentionally creates Text nodes by splitting it.
root.appendChild(document.createTextNode("aaa"));
root.appendChild(document.createTextNode("bbb"));

root.appendChild(document.createElement("child"));

root.appendChild(document.createTextNode(""));

{
    final var nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i));
    }

    // Result
    // ↓
    //[#text: aaa]
    //[#text: bbb]
    //[child: null]
    //[#text: ]
}

// Adjacent text nodes are combined. Empty Text nodes are deleted.
root.normalize();

{
    final var nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i));
    }

    // Result
    // ↓
    //[#text: aaabbb]
    //[child: null]
}

Node removeChild (Node oldChild)

从子列表中删除 oldChild 指示的子节点并返回它。 (机器翻译)

final var xml = """
        <root><child>abcd</child></root>
        """;

final var document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child>abcd</child>
//</root>
printDocument(document);

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]

final Node ret = root.removeChild(child);
System.out.println(ret); // [child: null]

//<root/>
printDocument(document);

Node replaceChild (Node newChild, Node oldChild)

用 newChild 替换子节点列表中的子节点 oldChild,并返回 oldChild 节点。 (机器翻译)

final var xml = """
        <root><child-a>abcd</child-a></root>
        """;

final var document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child-a>abcd</child-a>
//</root>
printDocument(document);

final Node root = document.getDocumentElement();
System.out.println(root); // [root: null]

final Node childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]

final Node childB = document.createElement("child-b");
childB.appendChild(document.createTextNode("XYZ"));

final Node ret = root.replaceChild(childB, childA);
System.out.println(ret); // [child-a: null]

//<root>
//    <child-b>XYZ</child-b>
//</root>
printDocument(document);

void setNodeValue (String nodeValue)

此节点的值取决于其类型;参见上表。 (机器翻译)

final var xml = """
        <root><child aa="AA"/></root>
        """;

final var document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child aa="AA"/>
//</root>
printDocument(document);

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]

final Node attr = child.getAttributes().item(0);
attr.setNodeValue("XYZ");

//<root>
//    <child aa="XYZ"/>
//</root>
printDocument(document);

void setPrefix (String prefix)

此节点的命名空间前缀,如果未指定,则为 null。 (机器翻译)

final var xml = """
        <ns:root xmlns:ns="sample"><ns:child/></ns:root>
        """;

final var document = DocumentBuilderFactory.newNSInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

//<ns:root xmlns:ns="sample">
//    <ns:child/>
//</ns:root>
printDocument(document);

final Node child = document.getElementsByTagName("ns:child").item(0);
System.out.println(child); // [ns:child: null]

child.setPrefix("xx");

//<ns:root xmlns:ns="sample">
//    <xx:child xmlns:xx="sample"/>
//</ns:root>
printDocument(document);

void setTextContent (String textContent)

该属性返回此节点及其后代的文本内容。 (机器翻译)

final var xml = """
        <root><child/></root>
        """;

final var document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

//<root>
//    <child/>
//</root>
printDocument(document);

final Node child = document.getElementsByTagName("child").item(0);
System.out.println(child); // [child: null]

child.setTextContent("abcd");

//<root>
//    <child>abcd</child>
//</root>
printDocument(document);

Object setUserData (String key, Object data, UserDataHandler handler)

将一个对象与此节点上的一个键关联起来。 (机器翻译)

final var xml = """
        <root>
            <child-a/>
            <child-b/>
        </root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final Node childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]

final Node childB = document.getElementsByTagName("child-b").item(0);
System.out.println(childB); // [child-b: null]

final var handler = new UserDataHandler() {
    @Override
    public void handle(short operation, String key, Object data, Node src, Node dst) {
        System.out.println("-- UserDataHandler.handle --");
        System.out.println(
                "operation = " + operation + " : key = " + key +
                        " : data = " + data + " : src = " + src + " : dst = " + dst);
    }
};

final var retA = childA.setUserData("a-key", "aaa", handler);
System.out.println(retA); // null

final var retB = childB.setUserData("b-key", "bbb", handler);
System.out.println(retB); // null

System.out.println(childA.getUserData("a-key")); // aaa
System.out.println(childA.getUserData("b-key")); // null

System.out.println(childB.getUserData("a-key")); // null
System.out.println(childB.getUserData("b-key")); // bbb

final var clonedNode = childA.cloneNode(false);

// Result
// ↓
//-- UserDataHandler.handle --
//operation = 1 : key = a-key : data = aaa : src = [child-a: null] : dst = [child-a: null]

final var renamedNode = document.renameNode(childB, null, "child-z");

// Result
// ↓
//-- UserDataHandler.handle --
//operation = 4 : key = b-key : data = bbb : src = [child-z: null] : dst = null

相关文章

To top of page