Labels

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>

<books>
<book id="1">
<name>java
</name>
</book>
<book id="2">
<name>perl
</name>
</book>
<book id="3">
<name>java 2
</name>
</book>
</books>

the XSD where you specify the id so that getElementById method can be used
<!ELEMENT name (#PCDATA)>

<!--- Put your DTDDoc comment here. -->
<!ELEMENT book (name)*>
<!ATTLIST book id ID #REQUIRED >

<!--- 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