Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting attribute/node in XML in java

Here's my XML:

<root>
   <A id='1'>
     <B>Blah</B>
     <C>Test</C>
   </A>
</root>

I would like to add under so my final XML would like:

<root>
   <A id='1'>
     <B>Blah</B>
     <C>Test</C>
     <D>New value</D>
    </A>
</root>

I can get the node in XPath using //Aand I am not sure how to add or edit the values once I get the node.

like image 377
ed1t Avatar asked Jun 24 '26 21:06

ed1t


1 Answers

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
StringReader xml = new StringReader("<root><A id='1'><B>Blah</B><C>Test</C></A></root>");
Document doc = db.parse(new InputSource(xml));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//A");
Element element = doc.createElement("D");
element.setTextContent("new value");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for(int i = 0; i < nodes.getLength(); i++) {  
    Node node = nodes.item(i);
    node.appendChild(element);
}
like image 177
Sahil Muthoo Avatar answered Jun 27 '26 12:06

Sahil Muthoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!