algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Read Modify XML,using the getElementById

<strong>xml a.xml to parse </strong>

<book id="1">
<book id="2">
<book id="3">
<name>java 2

the XSD where you specify the id so that getElementById method can be used

<!--- Put your DTDDoc comment here. -->
<!ELEMENT book (name)*>

<!--- Put your DTDDoc comment here. -->
<!ELEMENT books (book)*>

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//parse the xml file
Document doc = docBuilder.parse(new File("a.xml"));
doc.getElementById("1").getChildNodes().item(1).setTextContent("new book name");
Transformer transformer = TransformerFactory.newInstance().newTransformer(); StreamResult result = new StreamResult(new File("a.xml"));
//write the dom tree which is updated back to the same xml file
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

No comments:

Post a Comment

Search 24 Bytes