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 :
- Este artículo puede utilizar software de traducción para su comodidad. Consulte también la versión original en inglés.
Summary
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)
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)
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)
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)
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)
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)
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 ()
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 ()
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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.