Java Reference
In-Depth Information
Updating a Value in an XML Document
Problem
You want to change a value in an XML document element or attribute. The XML document is
on your filesystem and you need to persist the change.
Solution
Parse the document, use XPath to find the value you want to change, change the text content
of the node, and then use StreamResult with Transformer to write out the file again.
The solution is shown in Example 3-6 .
Example3-6.UpdateXMLValue.java
package com.sc.ch02.xpath;
import static java.lang.System.out;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class UpdateXMLValue {
public static void main(String[] args) throws Exception {
String xmlSource = "src/xml/ch02/Catalog.xml";
//find the topic titled 'Hamlet' and select its price.
String xpath = "/catalog/book[title='Hamlet']/price";
//this is the new price
String value = "8.95";
Search WWH ::




Custom Search