App下載
首頁(yè)javadomJava HTML/XML - 如何從父級(jí)刪除元素...

Java HTML/XML - 如何從父級(jí)刪除元素...

我們想知道如何從父級(jí)刪除元素。...
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;

public class Main {
  public static void main(String[] args) throws Exception {
    File xmlFile = new File("test.xml");
    Document document = readXmlDocument(xmlFile);
    makeChanges(document);
    Transformer transformer = createXmlTransformer();
    overwriteXmlFile(xmlFile, document, transformer);
  }
  private static void overwriteXmlFile(File xmlFile, Document document,
      Transformer transformer) throws FileNotFoundException,
      TransformerException {
    StreamResult result = new StreamResult(new PrintWriter(
        new FileOutputStream(xmlFile, false)));
    DOMSource source = new DOMSource(document);
    transformer.transform(source, result);
  }

  private static Transformer createXmlTransformer() throws Exception {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    return transformer;
  }

  private static void makeChanges(Document document) {
    Element root = document.getDocumentElement();
    root.setAttribute("test", "testvalue");
  }

  private static Document readXmlDocument(File xmlFile) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(xmlFile);
    return document;
  }
}