Java : Element (XML) 示例

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

注解 :

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

简介

Element 接口表示 HTML 或 XML 文档中的元素。元素可能具有与其关联的属性;由于 Element 接口继承自 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 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

String getAttribute (String name)

通过名称检索属性值。 (机器翻译)

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 var node = document.getElementsByTagName("child").item(0);
if (node instanceof Element element) {

    final var attrA = element.getAttribute("aa");
    System.out.println(attrA); // AA

    final var attrB = element.getAttribute("bb");
    System.out.println(attrB); // BB
}

Attr getAttributeNode (String name)

通过名称检索属性节点。 (机器翻译)

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 var node = document.getElementsByTagName("child").item(0);
if (node instanceof Element element) {

    final var attrA = element.getAttributeNode("aa");
    System.out.println(attrA); // aa="AA"

    final var attrB = element.getAttributeNode("bb");
    System.out.println(attrB); // bb="BB"
}

Attr getAttributeNodeNS (String namespaceURI, String localName)

通过本地名称和命名空间 URI 检索 Attr 节点。 (机器翻译)

final var xml = """
        <root xmlns:ns1="sample1" xmlns:ns2="sample2" >
            <child ns1:aa="AA1" ns2:aa="AA2" />
        </root>
        """;

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

final var node = document.getElementsByTagName("child").item(0);
if (node instanceof Element element) {

    final var attrA = element.getAttributeNodeNS("sample1", "aa");
    System.out.println(attrA); // ns1:aa="AA1"

    final var attrB = element.getAttributeNodeNS("sample2", "aa");
    System.out.println(attrB); // ns2:aa="AA2"
}

String getAttributeNS (String namespaceURI, String localName)

通过本地名称和命名空间 URI 检索属性值。 (机器翻译)

final var xml = """
        <root xmlns:ns1="sample1" xmlns:ns2="sample2" >
            <child ns1:aa="AA1" ns2:aa="AA2" />
        </root>
        """;

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

final var node = document.getElementsByTagName("child").item(0);
if (node instanceof Element element) {

    final var attrA = element.getAttributeNS("sample1", "aa");
    System.out.println(attrA); // AA1

    final var attrB = element.getAttributeNS("sample2", "aa");
    System.out.println(attrB); // AA2
}

NodeList getElementsByTagName (String name)

按文档顺序返回具有给定标签名称的所有后代元素的 NodeList。 (机器翻译)

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

            <child-c>
                <child-b/>
                <child-b/>
            </child-c>
        </root>
        """;

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

final var root = document.getDocumentElement();

final var nodesA = root.getElementsByTagName("child-a");
System.out.println("-- child-a --");
for (int i = 0; i < nodesA.getLength(); i++) {
    final var item = nodesA.item(i);
    System.out.println("node = " + item + " : parent = " + item.getParentNode());
}

// Result
// ↓
//-- child-a --
//node = [child-a: null] : parent = [root: null]

final var nodesB = root.getElementsByTagName("child-b");
System.out.println("-- child-b --");
for (int i = 0; i < nodesB.getLength(); i++) {
    final var item = nodesB.item(i);
    System.out.println("node = " + item + " : parent = " + item.getParentNode());
}

// Result
// ↓
//-- child-b --
//node = [child-b: null] : parent = [root: null]
//node = [child-b: null] : parent = [child-c: null]
//node = [child-b: null] : parent = [child-c: null]

final var nodesC = root.getElementsByTagName("child-c");
System.out.println("-- child-c --");
for (int i = 0; i < nodesC.getLength(); i++) {
    final var item = nodesC.item(i);
    System.out.println("node = " + item + " : parent = " + item.getParentNode());
}

// Result
// ↓
//-- child-c --
//node = [child-c: null] : parent = [root: null]

NodeList getElementsByTagNameNS (String namespaceURI, String localName)

按文档顺序返回具有给定本地名称和命名空间 URI 的所有后代元素的 NodeList。 (机器翻译)

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

            <child-b/>
            <ns:child-b/>
            <ns:child-b/>
        </root>
        """;

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

final var root = document.getDocumentElement();

final var nodesA = root.getElementsByTagName("child-a");
System.out.println("-- child-a --");
for (int i = 0; i < nodesA.getLength(); i++) {
    System.out.println(nodesA.item(i));
}

// Result
// ↓
//-- child-a --
//[child-a: null]
//[child-a: null]

final var nodesB1 = root.getElementsByTagName("child-b");
System.out.println("-- child-b --");
for (int i = 0; i < nodesB1.getLength(); i++) {
    System.out.println(nodesB1.item(i));
}

// Result
// ↓
//-- child-b --
//[child-b: null]

final var nodesB2 = root.getElementsByTagNameNS("sample", "child-b");
System.out.println("-- ns:child-b --");
for (int i = 0; i < nodesB2.getLength(); i++) {
    System.out.println(nodesB2.item(i));
}

// Result
// ↓
//-- ns:child-b --
//[ns:child-b: null]
//[ns:child-b: null]

TypeInfo getSchemaTypeInfo ()

与此元素相关的类型信息。 (机器翻译)

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

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

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    System.out.println(element.getSchemaTypeInfo()); // [child: null]

    final var attr = element.getAttributeNode("aa");
    System.out.println(attr.getSchemaTypeInfo()); // aa="AA"
}

String getTagName ()

元素的名称。 (机器翻译)

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.getTagName()); // root

final var child = root.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    System.out.println(element.getTagName()); // child
}

boolean hasAttribute (String name)

当此元素上指定了具有给定名称的属性或具有默认值时,返回 true,否则返回 false。 (机器翻译)

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 var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {

    System.out.println(element.hasAttribute("aa")); // true
    System.out.println(element.hasAttribute("bb")); // true
    System.out.println(element.hasAttribute("cc")); // false
}

boolean hasAttributeNS (String namespaceURI, String localName)

当此元素上指定了具有给定本地名称和命名空间 URI 的属性或具有默认值时返回 true,否则返回 false。 (机器翻译)

final var xml = """
        <root xmlns:ns1="sample1" xmlns:ns2="sample2">
            <child ns1:aa="AA" ns2:bb="BB"/>
        </root>
        """;

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

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {

    System.out.println(element.hasAttributeNS("sample1", "aa")); // true
    System.out.println(element.hasAttributeNS("sample2", "aa")); // false

    System.out.println(element.hasAttributeNS("sample1", "bb")); // false
    System.out.println(element.hasAttributeNS("sample2", "bb")); // true
}

void removeAttribute (String name)

根据名称删除属性。 (机器翻译)

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()));

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

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    element.removeAttribute("aa");
}

//<root>
//    <child bb="BB"/>
//</root>
printDocument(document);

Attr removeAttributeNode (Attr oldAttr)

删除指定的属性节点。 (机器翻译)

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()));

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

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    final var oldAttr = element.getAttributeNode("aa");
    System.out.println(oldAttr); // aa="AA"

    final var ret = element.removeAttributeNode(oldAttr);
    System.out.println(ret); // aa="AA"
}

//<root>
//    <child bb="BB"/>
//</root>
printDocument(document);

void removeAttributeNS (String namespaceURI, String localName)

通过本地名称和命名空间 URI 删除属性。 (机器翻译)

final var xml = """
        <root xmlns:ns1="sample1" xmlns:ns2="sample2" ><child ns1:aa="AA1" ns2:aa="AA2" /></root>
        """;

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

//<root xmlns:ns1="sample1" xmlns:ns2="sample2">
//    <child ns1:aa="AA1" ns2:aa="AA2"/>
//</root>
printDocument(document);

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    element.removeAttributeNS("sample1", "aa");
}

//<root xmlns:ns1="sample1" xmlns:ns2="sample2">
//    <child ns2:aa="AA2"/>
//</root>
printDocument(document);

void setAttribute (String name, String value)

添加新属性。 (机器翻译)

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

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

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

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    element.setAttribute("aa", "AA");
    element.setAttribute("bb", "BB");
    element.setAttribute("cc", "CC");
}

//<root>
//    <child aa="AA" bb="BB" cc="CC"/>
//</root>
printDocument(document);

Attr setAttributeNode (Attr newAttr)

添加一个新的属性节点。 (机器翻译)

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

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

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

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    final var attr1 = document.createAttribute("aa");
    attr1.setValue("AA");

    final var ret1 = element.setAttributeNode(attr1);
    System.out.println(ret1); // null

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

    final var attr2 = document.createAttribute("bb");
    attr2.setValue("BB-1");

    final var ret2 = element.setAttributeNode(attr2);
    System.out.println(ret2); // null

    //<root>
    //    <child aa="AA" bb="BB-1"/>
    //</root>
    printDocument(document);

    final var attr3 = document.createAttribute("bb");
    attr3.setValue("BB-2");

    final var ret3 = element.setAttributeNode(attr3);
    System.out.println(ret3); // bb="BB-1"

    //<root>
    //    <child aa="AA" bb="BB-2"/>
    //</root>
    printDocument(document);
}

Attr setAttributeNodeNS (Attr newAttr)

添加新属性。 (机器翻译)

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

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

//<root xmlns:ns1="sample1" xmlns:ns2="sample2">
//    <child/>
//</root>
printDocument(document);

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {

    final var attr1 = document.createAttributeNS("sample1", "ns1:aa");
    attr1.setValue("AA-1");

    final var ret1 = element.setAttributeNode(attr1);
    System.out.println(ret1); // null

    //<root xmlns:ns1="sample1" xmlns:ns2="sample2">
    //    <child ns1:aa="AA-1"/>
    //</root>
    printDocument(document);

    final var attr2 = document.createAttributeNS("sample1", "ns1:aa");
    attr2.setValue("AA-2");

    final var ret2 = element.setAttributeNode(attr2);
    System.out.println(ret2); // ns1:aa="AA-1"

    //<root xmlns:ns1="sample1" xmlns:ns2="sample2">
    //    <child ns1:aa="AA-2"/>
    //</root>
    printDocument(document);

    final var attr3 = document.createAttributeNS("sample2", "ns2:aa");
    attr3.setValue("AA-3");

    final var ret3 = element.setAttributeNode(attr3);
    System.out.println(ret3); // null

    //<root xmlns:ns1="sample1" xmlns:ns2="sample2">
    //    <child ns1:aa="AA-2" ns2:aa="AA-3"/>
    //</root>
    printDocument(document);
}

void setAttributeNS (String namespaceURI, String qualifiedName, String value)

添加新属性。 (机器翻译)

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

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

//<root xmlns:ns1="sample1" xmlns:ns2="sample2">
//    <child/>
//</root>
printDocument(document);

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    element.setAttributeNS("sample1", "ns1:aa", "AA-1");
    element.setAttributeNS("sample2", "ns2:aa", "AA-2");
}

//<root xmlns:ns1="sample1" xmlns:ns2="sample2">
//    <child ns1:aa="AA-1" ns2:aa="AA-2"/>
//</root>
printDocument(document);

void setIdAttribute (String name, boolean isId)

如果参数 isId 为 true,则此方法将指定的属性声明为用户确定的 ID 属性。 (机器翻译)

final var xml = """
        <root><child id-a="ID-A"/></root>
        """;

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

//<root>
//    <child id-a="ID-A"/>
//</root>
printDocument(document);

final var before = document.getElementById("ID-A");
System.out.println(before); // null

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    element.setIdAttribute("id-a", true);
}

final var after = document.getElementById("ID-A");
System.out.println(after); // [child: null]

//<root>
//    <child id-a="ID-A"/>
//</root>
printDocument(document);

void setIdAttributeNode (Attr idAttr, boolean isId)

如果参数 isId 为 true,则此方法将指定的属性声明为用户确定的 ID 属性。 (机器翻译)

final var xml = """
        <root><child id-a="ID-A"/></root>
        """;

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

//<root>
//    <child id-a="ID-A"/>
//</root>
printDocument(document);

final var before = document.getElementById("ID-A");
System.out.println(before); // null

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    final var attr = element.getAttributeNode("id-a");
    System.out.println(attr); // id-a="ID-A"

    element.setIdAttributeNode(attr, true);
}

final var after = document.getElementById("ID-A");
System.out.println(after); // [child: null]

//<root>
//    <child id-a="ID-A"/>
//</root>
printDocument(document);

void setIdAttributeNS (String namespaceURI, String localName, boolean isId)

如果参数 isId 为 true,则此方法将指定的属性声明为用户确定的 ID 属性。 (机器翻译)

final var xml = """
        <root xmlns:ns="sample"><child ns:id-a="ID-A"/></root>
        """;

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

//<root xmlns:ns="sample">
//    <child ns:id-a="ID-A"/>
//</root>
printDocument(document);

final var before = document.getElementById("ID-A");
System.out.println(before); // null

final var child = document.getElementsByTagName("child").item(0);
if (child instanceof Element element) {
    element.setIdAttributeNS("sample", "id-a", true);
}

final var after = document.getElementById("ID-A");
System.out.println(after); // [child: null]

//<root xmlns:ns="sample">
//    <child ns:id-a="ID-A"/>
//</root>
printDocument(document);

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