Java : Attr (XML) con ejemplos

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

Nota :


Summary

La interfaz Attr representa un atributo en un objeto Element. Normalmente, los valores permitidos para el atributo se definen en un esquema asociado con el 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 attrA = document.createAttribute("aa");
attrA.setValue("AA");
System.out.println(attrA); // aa="AA"

child.setAttributeNode(attrA);

final var attrB = document.createAttribute("bb");
attrB.setValue("BB");
System.out.println(attrB); // bb="BB"

child.setAttributeNode(attrB);

//<root>
//    <child aa="AA" bb="BB"/>
//</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 getName ()

Devuelve el nombre de este atributo. (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) {
    final var attr = element.getAttributeNode("aa");
    System.out.println(attr); // aa="AA"

    System.out.println(attr.getName()); // aa
    System.out.println(attr.getValue()); // AA
    System.out.println(attr.getSchemaTypeInfo()); // aa="AA"
}

Element getOwnerElement ()

El nodo Elemento al que está asociado este atributo o nulo si este atributo no está en uso. (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) {
    final var attr = element.getAttributeNode("aa");
    System.out.println(attr); // aa="AA"

    final var owner = attr.getOwnerElement();
    System.out.println(owner); // [child: null]
    System.out.println(owner.isSameNode(child)); // true
}

TypeInfo getSchemaTypeInfo ()

La información de tipo asociada con este atributo. (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) {
    final var attr = element.getAttributeNode("aa");
    System.out.println(attr); // aa="AA"

    System.out.println(attr.getName()); // aa
    System.out.println(attr.getValue()); // AA
    System.out.println(attr.getSchemaTypeInfo()); // aa="AA"
}

boolean getSpecified ()

Verdadero si a este atributo se le asignó explícitamente un valor en el documento de instancia, falso en caso contrario. (Traducción automática)

final var xml = """
        <!DOCTYPE root [
          <!ATTLIST child answer (yes|no) "no">
        ]>
        <root>
            <child a="A"/>
        </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); // [child: null]

    final var attrAnswer = element.getAttributeNode("answer");
    System.out.println(attrAnswer); // answer="no"
    System.out.println(attrAnswer.getSpecified()); // false

    final var attrA = element.getAttributeNode("a");
    System.out.println(attrA); // a="A"
    System.out.println(attrA.getSpecified()); // true
}

String getValue ()

Al recuperarlo, el valor del atributo se devuelve como una cadena. (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) {
    final var attr = element.getAttributeNode("aa");
    System.out.println(attr); // aa="AA"

    System.out.println(attr.getName()); // aa
    System.out.println(attr.getValue()); // AA
    System.out.println(attr.getSchemaTypeInfo()); // aa="AA"
}

boolean isId ()

Devuelve si se sabe que este atributo es de tipo ID (es decir, que contiene un identificador para su elemento propietario) o no. (Traducción automática)

final var xml = """
        <!DOCTYPE root [
          <!ATTLIST child id-a ID "ID-A">
        ]>
        <root>
            <child id-a="ID-A" b="B"/>
        </root>
        """;

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

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

final var attrId = child.getAttributeNode("id-a");
System.out.println(attrId); // id-a="ID-A"
System.out.println(attrId.isId()); // true

final var attrB = child.getAttributeNode("b");
System.out.println(attrB); // b="B"
System.out.println(attrB.isId()); // false

void setValue (String value)

Al recuperarlo, el valor del atributo se devuelve como una cadena. (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) {

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

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

    attrA.setValue("XYZ");
    System.out.println(attrA); // aa="XYZ"

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

    final var attrB = document.createAttribute("bb");
    attrB.setValue("BB");
    System.out.println(attrB); // bb="BB"

    element.setAttributeNode(attrB);

    //<root>
    //    <child aa="XYZ" bb="BB"/>
    //</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