App下載
首頁javadomJava HTML/XML - 如何將節(jié)點內(nèi)容編輯為XML文件

Java HTML/XML - 如何將節(jié)點內(nèi)容編輯為XML文件

我們想知道如何將節(jié)點內(nèi)容編輯為XML文件。
import java.io.File;

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 javax.xml.transform.stream.StreamResult;

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 ++) {
          ((Element)nodes.item(i)).setTextContent("Modified");
      }
      xmlDoc.getDocumentElement().normalize();
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}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");
    }
}