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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With