Java : Document (XML) con ejemplos

Document (Java SE 22 & JDK 22) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de Document.

Nota :


Summary

La interfaz de documento representa el documento HTML o XML completo. Conceptualmente, es la raíz del árbol del documento y proporciona el acceso principal a los datos del documento. (Traducción automática)

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

Consulte el siguiente enlace.

Methods

Node adoptNode (Node source)

Intenta adoptar un nodo de otro documento a este documento. (Traducción automática)

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)

Crea un Attr del nombre dado. (Traducción automática)

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)

Crea un atributo del nombre calificado y el URI del espacio de nombres dados. (Traducción automática)

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)

Crea un nodo CDATASection cuyo valor es la cadena especificada. (Traducción automática)

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)

Crea un nodo Comentario dada la cadena especificada. (Traducción automática)

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

Crea un objeto DocumentFragment vacío. (Traducción automática)

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)

Crea un elemento del tipo especificado. (Traducción automática)

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)

Crea un elemento con el nombre calificado y el URI del espacio de nombres dados. (Traducción automática)

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)

Crea un objeto EntityReference. (Traducción automática)

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)

Crea un nodo ProcessingInstruction dado el nombre y las cadenas de datos especificados. (Traducción automática)

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)

Crea un nodo de texto dada la cadena especificada. (Traducción automática)

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

La declaración de tipo de documento (ver DocumentType) asociada a este documento. (Traducción automática)

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

Este es un atributo de conveniencia que permite el acceso directo al nodo secundario que es el elemento del documento. (Traducción automática)

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

La ubicación del documento o nulo si no está definido o si el documento se creó utilizando DOMImplementation.createDocument. (Traducción automática)

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

La configuración utilizada cuando se invoca Document.normalizeDocument(). (Traducción automática)

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)

Devuelve el elemento que tiene un atributo ID con el valor dado. (Traducción automática)

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)

Devuelve una lista de nodos de todos los elementos en el orden del documento con un nombre de etiqueta determinado y que están contenidos en el documento. (Traducción automática)

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)

Devuelve una lista de nodos de todos los elementos con un nombre local y un URI de espacio de nombres determinados en el orden del documento. (Traducción automática)

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

El objeto DOMImplementation que maneja este documento. (Traducción automática)

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

Un atributo que especifica la codificación utilizada para este documento en el momento del análisis. (Traducción automática)

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

Un atributo que especifica si se aplica o no la comprobación de errores. (Traducción automática)

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

Un atributo que especifica, como parte de la declaración XML, la codificación de este documento. (Traducción automática)

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

Un atributo que especifica, como parte de la declaración XML, si este documento es independiente. (Traducción automática)

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

Un atributo que especifica, como parte de la declaración XML, el número de versión de este documento. (Traducción automática)

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)

Importa un nodo de otro documento a este documento, sin alterar ni eliminar el nodo de origen del documento original; este método crea una nueva copia del nodo de origen. (Traducción automática)

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

Este método actúa como si el documento estuviera pasando por un ciclo de guardado y carga, poniendo el documento en un formato "normal". (Traducción automática)

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)

Cambiar el nombre de un nodo existente de tipo ELEMENT_NODE o ATTRIBUTE_NODE. (Traducción automática)

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)

La ubicación del documento o nulo si no está definido o si el documento se creó utilizando DOMImplementation.createDocument. (Traducción automática)

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)

Un atributo que especifica si se aplica o no la comprobación de errores. (Traducción automática)

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)

Un atributo que especifica, como parte de la declaración XML, si este documento es independiente. (Traducción automática)

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)

Un atributo que especifica, como parte de la declaración XML, el número de versión de este documento. (Traducción automática)

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

Consulte el siguiente enlace.


Related posts

To top of page