I have an xml as String
<color>
<name>black</name>
<color>
I want to add an attribute to root node and save a xml as String again.
<color id="1">
<name>black</name>
<color>
But I can't. Here is my code
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
String xml = "<color><name>black</name></color>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document document = builder.parse(is);
Element element = (Element) document.getFirstChild();
element.setAttribute("id", nwp);
String result = document.toString();
System.out.println(result);
The output is [#document: null]. Help me please resolve my problem
No comments:
Post a Comment