Eksempel:
package may;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.SAXException;
public class XmlMod {
public static void createFile(String fnm) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter(fnm));
pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
pw.println("<data>");
pw.println(" <x a=\"177\"/>");
pw.println("</data>");
pw.close();
}
public static void displayFile(String fnm) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fnm));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
private static void changeFile(String oldfnm, int oldattr, String newfnm, int newattr) throws ParserConfigurationException, SAXException, IOException, ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException, XPathExpressionException {
// read
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(oldfnm);
// change
XPath xpath = XPathFactory.newInstance().newXPath();
Element x = (Element)xpath.evaluate("/data/x[@a=" + oldattr + "]", doc.getDocumentElement(), XPathConstants.NODE);
x.setAttribute("a", Integer.toString(newattr));
// write
DOMImplementation impl = DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0");
DOMImplementationLS feature = (DOMImplementationLS)impl.getFeature("LS","3.0");
LSSerializer ser = feature.createLSSerializer();
LSOutput output = feature.createLSOutput();
output.setCharacterStream(new PrintWriter(newfnm));
ser.write(doc, output);
}
public static void main(String[] args) throws Exception {
createFile("C:\\bef.xml");
displayFile("C:\\bef.xml");
changeFile("C:\\bef.xml", 177, "C:\\aft.xml", 299);
displayFile("C:\\aft.xml");
}
}