Java : Attr (XML) with Examples

Attr (Java SE 22 & JDK 22) with Examples.
You will find code examples on most Attr methods.


Summary

The Attr interface represents an attribute in an Element object. Typically the allowable values for the attribute are defined in a schema associated with the document.

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

Please see the link below.

Methods

String getName ()

Returns the name of this attribute.

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

The Element node this attribute is attached to or null if this attribute is not in use.

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

The type information associated with this attribute.

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

True if this attribute was explicitly given a value in the instance document, false otherwise.

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

On retrieval, the value of the attribute is returned as a string.

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

Returns whether this attribute is known to be of type ID (i.e. to contain an identifier for its owner element) or not.

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)

On retrieval, the value of the attribute is returned as a string.

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

Please see the link below.


Related posts

To top of page