Java : Document (XML) 示例

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

注解 :

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

简介

Document 接口代表整个 HTML 或 XML 文档。从概念上讲,它是文档树的根,并提供对文档数据的主要访问。 (机器翻译)

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

Node adoptNode (Node source)

尝试将另一个文档中的节点引入到该文档中。 (机器翻译)

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

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

final var docA = builder.newDocument();
final var docB = builder.parse(new ByteArrayInputStream(xml.getBytes()));

System.out.println(docA.getDocumentElement()); // null

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

final var source = docB.getDocumentElement();

try {
    docA.appendChild(source);
} catch (DOMException e) {
    System.out.println(e);
}

// Result
// ↓
//org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR:
// A node is used in a different document than the one that created it.

final var ret = docA.adoptNode(source);
System.out.println(ret); // [root: null]

System.out.println(docA.appendChild(ret)); // [root: null]

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

System.out.println(docB.getDocumentElement()); // null

Attr createAttribute (String name)

创建给定名称的 Attr。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var attrA = document.createAttribute("attr-a");
System.out.println(attrA); // attr-a=""

attrA.setValue("aaa");
System.out.println(attrA); // attr-a="aaa"

final var attrB = document.createAttribute("attr-b");
System.out.println(attrB); // attr-b=""

attrB.setValue("bbb");
System.out.println(attrB); // attr-b="bbb"

root.setAttributeNode(attrA);
root.setAttributeNode(attrB);

//<root attr-a="aaa" attr-b="bbb"/>
printDocument(document);

Attr createAttributeNS (String namespaceURI, String qualifiedName)

创建给定限定名称和命名空间 URI 的属性。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElementNS("http://example.com", "ns:root");
System.out.println(root); // [ns:root: null]

document.appendChild(root);

final var attrA = document.createAttributeNS("http://example.com", "ns:attr-a");
System.out.println(attrA); // ns:attr-a=""

attrA.setValue("aaa");
System.out.println(attrA); // ns:attr-a="aaa"

root.setAttributeNode(attrA);

//<ns:root xmlns:ns="http://example.com" ns:attr-a="aaa"/>
printDocument(document);

CDATASection createCDATASection (String data)

创建一个其值为指定字符串的 CDATASection 节点。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var cdataSection = document.createCDATASection("<?>");
System.out.println(cdataSection); // [#cdata-section: <?>]

root.appendChild(cdataSection);

//<root><![CDATA[<?>]]></root>
printDocument(document);

Comment createComment (String data)

根据指定的字符串创建一个 Comment 节点。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var commentA = document.createComment("aaa");
System.out.println(commentA); // [#comment: aaa]

root.appendChild(commentA);

//<root>
//    <!--aaa-->
//</root>
printDocument(document);

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

//<root>
//    <!--aaa-->
//    <child/>
//    <!--bbb-->
//</root>
printDocument(document);

DocumentFragment createDocumentFragment ()

创建一个空的 DocumentFragment 对象。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

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

documentFragment.appendChild(document.createElement("child-a"));
documentFragment.appendChild(document.createElement("child-b"));

root.appendChild(documentFragment);

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

Element createElement (String tagName)

创建指定类型的元素。 (机器翻译)

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

final var document = builder.newDocument();

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

document.appendChild(root);

root.appendChild(document.createElement("child-a"));
root.appendChild(document.createElement("child-b"));

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

Element createElementNS (String namespaceURI, String qualifiedName)

创建给定限定名称和命名空间 URI 的元素。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElementNS("http://example.com", "ns:root");
System.out.println(root); // [ns:root: null]

document.appendChild(root);

final var attrA = document.createAttributeNS("http://example.com", "ns:attr-a");
System.out.println(attrA); // ns:attr-a=""

attrA.setValue("aaa");
System.out.println(attrA); // ns:attr-a="aaa"

root.setAttributeNode(attrA);

//<ns:root xmlns:ns="http://example.com" ns:attr-a="aaa"/>
printDocument(document);

EntityReference createEntityReference (String name)

创建一个 EntityReference 对象。 (机器翻译)

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

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

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

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

final var entityReferenceA = document.createEntityReference("aaa");
System.out.println(entityReferenceA); // [aaa: null]

root.appendChild(entityReferenceA);

final var entityReferenceX = document.createEntityReference("xxx");
System.out.println(entityReferenceX); // [xxx: null]

root.appendChild(entityReferenceX);

//<root/>
printDocument(document);

final var domImpl = builder.getDOMImplementation();
if (domImpl.getFeature("LS", "3.0") instanceof DOMImplementationLS ls) {
    final var serializer = ls.createLSSerializer();
    final var str = serializer.writeToString(document);

    //<?xml version="1.0" encoding="UTF-16"?><!DOCTYPE root [
    //<!ENTITY aaa 'bbb'>
    //<!ENTITY xxx 'yyy'>
    //]>
    //<root>&aaa;&xxx;</root>
    System.out.println(str);
}

ProcessingInstruction createProcessingInstruction (String target, String data)

根据指定的名称和数据字符串创建一个 ProcessingInstruction 节点。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var processingInstruction =
        document.createProcessingInstruction("target", "data");
System.out.println(processingInstruction); // [target: data]

root.appendChild(processingInstruction);

//<root>
//    <?target data?>
//</root>
printDocument(document);

Text createTextNode (String data)

根据指定的字符串创建一个文本节点。 (机器翻译)

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

final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

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

root.appendChild(text);

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

DocumentType getDoctype ()

与此文档相关的文档类型声明(参见DocumentType)。 (机器翻译)

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

Files.writeString(dtd, """
        <!ENTITY aaa "bbb">
        <!ENTITY xxx "yyy">
        """);

final var xml = """
        <!DOCTYPE root SYSTEM "file:///R:/java-work/sample.dtd">
        <root/>
        """;

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

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

final var docType = document.getDoctype();

System.out.println(docType); // [root: null]
System.out.println(docType.getSystemId()); // file:///R:/java-work/sample.dtd

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

// Result
// ↓
//-- entities --
//[aaa: null]
//[xxx: null]

Element getDocumentElement ()

这是一个便捷属性,允许直接访问文档的文档元素的子节点。 (机器翻译)

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

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

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

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

String getDocumentURI ()

文档的位置;如果未定义或者使用 DOMImplementation.createDocument 创建文档,则为空。 (机器翻译)

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

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

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

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

final var uri = document.getDocumentURI();
System.out.println(uri); // file:/R:/java-work/sample.xml

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

DOMConfiguration getDomConfig ()

调用 Document.normalizeDocument() 时使用的配置。 (机器翻译)

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

final var document = builder.newDocument();

final var domConfig = document.getDomConfig();
final var names = domConfig.getParameterNames();

for (int i = 0; i < names.getLength(); i++) {
    final var name = names.item(i);
    final var param = domConfig.getParameter(name);
    System.out.println(name + " : " + param);
}

// Result
// ↓
//comments : true
//datatype-normalization : false
//cdata-sections : true
//entities : true
//split-cdata-sections : true
//namespaces : true
//validate : false
//infoset : false
//normalize-characters : false
//canonical-form : false
//validate-if-schema : false
//check-character-normalization : false
//well-formed : true
//namespace-declarations : true
//element-content-whitespace : true
//error-handler : null
//schema-type : null
//schema-location : null
//resource-resolver : null
//http://apache.org/xml/properties/internal/entity-resolver : null
//http://apache.org/xml/properties/internal/grammar-pool : null
//http://apache.org/xml/properties/security-manager : jdk.xml.internal.XMLSecurityManager@3fc79729
//http://apache.org/xml/properties/internal/symbol-table : com.sun.org.apache.xerces.internal.util.SymbolTable@34f6515b
//http://apache.org/xml/features/validation/schema/augment-psvi : true

Element getElementById (String elementId)

返回具有给定值的 ID 属性的元素。 (机器翻译)

final var xml = """
        <!DOCTYPE root [
          <!ATTLIST child id-x ID "ID-X">
        ]>
        <root>
            <child>AAA</child>
            <xxx>
                <child id-x="ID-X">BBB</child>
                <child>CCC</child>
            </xxx>
        </root>
        """;

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

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

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

final var nodes = document.getElementsByTagName("child");
System.out.println("-- nodes --");
for (int i = 0; i < nodes.getLength(); i++) {
    final var node = nodes.item(i);
    System.out.println(node + " : " + node.getTextContent());
}

// Result
// ↓
//-- nodes --
//[child: null] : AAA
//[child: null] : BBB
//[child: null] : CCC

NodeList getElementsByTagName (String tagname)

返回按文档顺序包含具有给定标签名称且包含在文档中的所有元素的 NodeList。 (机器翻译)

final var xml = """
        <!DOCTYPE root [
          <!ATTLIST child id-x ID "ID-X">
        ]>
        <root>
            <child>AAA</child>
            <xxx>
                <child id-x="ID-X">BBB</child>
                <child>CCC</child>
            </xxx>
        </root>
        """;

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

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

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

final var nodes = document.getElementsByTagName("child");
System.out.println("-- nodes --");
for (int i = 0; i < nodes.getLength(); i++) {
    final var node = nodes.item(i);
    System.out.println(node + " : " + node.getTextContent());
}

// Result
// ↓
//-- nodes --
//[child: null] : AAA
//[child: null] : BBB
//[child: null] : CCC

NodeList getElementsByTagNameNS (String namespaceURI, String localName)

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

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

final var factory = DocumentBuilderFactory.newNSInstance();
final var builder = factory.newDocumentBuilder();

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

final var child1 = document.getElementsByTagNameNS("sample1", "child").item(0);
System.out.println(child1); // [ns1:child: null]
System.out.println(child1.getTextContent()); // AAA

final var child2 = document.getElementsByTagNameNS("sample2", "child").item(0);
System.out.println(child2); // [ns2:child: null]
System.out.println(child2.getTextContent()); // BBB

DOMImplementation getImplementation ()

处理此文档的 DOMImplementation 对象。 (机器翻译)

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

final var document = builder.newDocument();

final var domImpl = document.getImplementation();
System.out.println(domImpl.hasFeature("LS", "3.0")); // true

final var ret = domImpl.getFeature("LS", "3.0") instanceof DOMImplementationLS;
System.out.println(ret); // true

String getInputEncoding ()

指定解析时此文档所用的编码的属性。 (机器翻译)

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

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

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

System.out.println(document.getInputEncoding()); // UTF-8

boolean getStrictErrorChecking ()

指定是否强制执行错误检查的属性。 (机器翻译)

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

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

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

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

{
    System.out.println(document.getStrictErrorChecking()); // true

    try {
        document.createElement("<?>");
    } catch (DOMException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //org.w3c.dom.DOMException: INVALID_CHARACTER_ERR:
    // An invalid or illegal XML character is specified.
}

document.setStrictErrorChecking(false);

{
    System.out.println(document.getStrictErrorChecking()); // false

    final var element = document.createElement("<?>");
    root.appendChild(element);

    //<root>
    //    abcd
    //    <<?>/>
    //</root>
    printDocument(document);
}

String getXmlEncoding ()

作为 XML 声明的一部分,指定此文档的编码的属性。 (机器翻译)

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

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

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

    System.out.println(document.getXmlEncoding()); // null
}
{
    final var xml = """
            <?xml version="1.0" encoding="UTF-8"?>
            <root/>
            """;

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

    System.out.println(document.getXmlEncoding()); // UTF-8
}
{
    final var xml = """
            <?xml version="1.0" encoding="Shift_JIS"?>
            <root/>
            """;

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

    System.out.println(document.getXmlEncoding()); // Shift_JIS
}

boolean getXmlStandalone ()

作为 XML 声明的一部分,指定该文档是否独立的属性。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var transformer = TransformerFactory.newInstance().newTransformer();

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

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

System.out.println(document.getXmlStandalone()); // false

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

    //<?xml version="1.0" encoding="UTF-8" standalone="no"?><root/>
    System.out.println(result.getWriter());
}

document.setXmlStandalone(true);
System.out.println(document.getXmlStandalone()); // true

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

    //<?xml version="1.0" encoding="UTF-8"?><root/>
    System.out.println(result.getWriter());
}

String getXmlVersion ()

作为 XML 声明的一部分,指定此文档的版本号的属性。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var transformer = TransformerFactory.newInstance().newTransformer();

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

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

System.out.println(document.getXmlVersion()); // 1.0

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

    //<?xml version="1.0" encoding="UTF-8" standalone="no"?><root/>
    System.out.println(result.getWriter());
}

document.setXmlVersion("1.1");
System.out.println(document.getXmlVersion()); // 1.1

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

    //<?xml version="1.1" encoding="UTF-8" standalone="no"?><root/>
    System.out.println(result.getWriter());
}

Node importNode (Node importedNode, boolean deep)

将节点从另一个文档导入到此文档,而不改变或删除原始文档中的源节点;此方法会创建源节点的新副本。 (机器翻译)

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

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

final var docA = builder.newDocument();
final var docB = builder.parse(new ByteArrayInputStream(xml.getBytes()));

System.out.println(docA.getDocumentElement()); // null

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

final var source = docB.getDocumentElement();

try {
    docA.appendChild(source);
} catch (DOMException e) {
    System.out.println(e);
}

// Result
// ↓
//org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR:
// A node is used in a different document than the one that created it.

final var ret = docA.importNode(source, true);
System.out.println(ret); // [root: null]
System.out.println(docA.appendChild(ret)); // [root: null]

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

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

void normalizeDocument ()

此方法的作用就像文档正在经历保存和加载循环,将文档置于“正常”形式。 (机器翻译)

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

final var root = document.createElement("root");
document.appendChild(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();
    System.out.println("-- nodes --");
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i));
    }

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

// Adjacent text nodes are combined. Empty Text nodes are deleted.
document.normalizeDocument();

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

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

Node renameNode (Node n, String namespaceURI, String qualifiedName)

重命名类型为 ELEMENT_NODE 或 ATTRIBUTE_NODE 的现有节点。 (机器翻译)

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

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

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

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

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

final var ret = document.renameNode(childA, null, "child-z");
System.out.println(ret); // [child-z: null]

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

void setDocumentURI (String documentURI)

文档的位置;如果未定义或者使用 DOMImplementation.createDocument 创建文档,则为空。 (机器翻译)

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

final var document = builder.newDocument();

System.out.println(document.getDocumentURI()); // null

document.setDocumentURI("http://www.example.com");

System.out.println(document.getDocumentURI()); // http://www.example.com

void setStrictErrorChecking (boolean strictErrorChecking)

指定是否强制执行错误检查的属性。 (机器翻译)

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

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

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

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

{
    System.out.println(document.getStrictErrorChecking()); // true

    try {
        document.createElement("<?>");
    } catch (DOMException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //org.w3c.dom.DOMException: INVALID_CHARACTER_ERR:
    // An invalid or illegal XML character is specified.
}

document.setStrictErrorChecking(false);

{
    System.out.println(document.getStrictErrorChecking()); // false

    final var element = document.createElement("<?>");
    root.appendChild(element);

    //<root>
    //    abcd
    //    <<?>/>
    //</root>
    printDocument(document);
}

void setXmlStandalone (boolean xmlStandalone)

作为 XML 声明的一部分,指定该文档是否独立的属性。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var transformer = TransformerFactory.newInstance().newTransformer();

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

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

System.out.println(document.getXmlStandalone()); // false

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

    //<?xml version="1.0" encoding="UTF-8" standalone="no"?><root/>
    System.out.println(result.getWriter());
}

document.setXmlStandalone(true);
System.out.println(document.getXmlStandalone()); // true

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

    //<?xml version="1.0" encoding="UTF-8"?><root/>
    System.out.println(result.getWriter());
}

void setXmlVersion (String xmlVersion)

作为 XML 声明的一部分,指定此文档的版本号的属性。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var transformer = TransformerFactory.newInstance().newTransformer();

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

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

System.out.println(document.getXmlVersion()); // 1.0

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

    //<?xml version="1.0" encoding="UTF-8" standalone="no"?><root/>
    System.out.println(result.getWriter());
}

document.setXmlVersion("1.1");
System.out.println(document.getXmlVersion()); // 1.1

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

    //<?xml version="1.1" encoding="UTF-8" standalone="no"?><root/>
    System.out.println(result.getWriter());
}

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