3

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.

2
  • 2
    There's many similar questions, please look around first. What technologies do you use and how is the value for the new node supplied? This is rather important to know. Do you use SAX, StAX, DOM, JDOM...? Are your parsing, transforming using XSLT, binding with JAXB? Commented Oct 27, 2011 at 14:34
  • I'm using DOM. I'm not using XSLT. Commented Oct 27, 2011 at 14:49

3 Answers 3

4
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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Check this method of the Node interface from DOM. Element extends this, so you'll first need to obtain the Element for A. Use this method on your Document instance, or some other suitable method from the class, to create the desired D element, then set its contents.

Comments

0

Apart from using the DOM API directly, you can also use jOOX, a simple wrapper library for DOM, that I have created:

// With css-style selectors
$(document).find("A").append("<D>New value</D>");

// With XPath
$(document).xpath("//A").append("<D>New value</D>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.