Java : Element (XML) con ejemplos

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

Nota :


Summary

La interfaz Element representa un elemento en un documento HTML o XML. Los elementos pueden tener atributos asociados a ellos; dado que la interfaz Element hereda de Node, el atributo de interfaz genérica de Node se puede utilizar para recuperar el conjunto de todos los atributos de un elemento. (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

String getAttribute (String name)

Recupera un valor de atributo por nombre. (Traducción automática)

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)

Recupera un nodo de atributo por nombre. (Traducción automática)

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)

Recupera un nodo Attr por nombre local y URI de espacio de nombres. (Traducción automática)

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)

Recupera un valor de atributo por nombre local y URI de espacio de nombres. (Traducción automática)

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)

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

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)

Devuelve una lista de nodos de todos los elementos descendientes 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: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 ()

La información de tipo asociada a este elemento. (Traducción automática)

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

El nombre del elemento. (Traducción automática)

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)

Devuelve verdadero cuando se especifica un atributo con un nombre determinado en este elemento o tiene un valor predeterminado, falso en caso contrario. (Traducción automática)

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)

Devuelve verdadero cuando se especifica un atributo con un nombre local y un URI de espacio de nombres determinados en este elemento o tiene un valor predeterminado; falso en caso contrario. (Traducción automática)

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)

Elimina un atributo por nombre. (Traducción automática)

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)

Elimina el nodo de atributo especificado. (Traducción automática)

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)

Elimina un atributo por nombre local y URI de espacio de nombres. (Traducción automática)

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)

Añade un nuevo atributo. (Traducción automática)

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)

Agrega un nuevo nodo de atributo. (Traducción automática)

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)

Añade un nuevo atributo. (Traducción automática)

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)

Añade un nuevo atributo. (Traducción automática)

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)

Si el parámetro isId es verdadero, este método declara que el atributo especificado es un atributo ID determinado por el usuario. (Traducción automática)

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)

Si el parámetro isId es verdadero, este método declara que el atributo especificado es un atributo ID determinado por el usuario. (Traducción automática)

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)

Si el parámetro isId es verdadero, este método declara que el atributo especificado es un atributo ID determinado por el usuario. (Traducción automática)

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

Consulte el siguiente enlace.


Related posts

To top of page