Java HTML / XML How to - Edit a node content into an XML file


We would like to know how to edit a node content into an XML file.


/* w  ww . ja v a  2  s. com*/

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = factory.newDocumentBuilder();
      Document xmlDoc = docBuilder.parse(new File("sample.xml"));
      NodeList nodes = xmlDoc.getElementsByTagName("fr");
      for (int i = 0, length = nodes.getLength(); i < length; i ++) {
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{}indent-amount", "4");
      DOMSource domSource = new DOMSource(xmlDoc);
      StreamResult result = new StreamResult(new File("sample.xml"));
      transformer.transform(domSource, result);
      System.out.println("Modification Done");