App下載
首頁(yè)javasaxJava HTML/XML - 如何使用String替換XML文檔中的元素

Java HTML/XML - 如何使用String替換XML文檔中的元素

我們想知道如何使用String替換XML文檔中的元素。
import java.io.ByteArrayInputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

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

public class Main {
  public static void main(final String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse(new ByteArrayInputStream(( //
        "<?xml version=\"1.0\"?>" + //
            "<people>" + //
            "<person><name>First Person Name</name></person>" + //
            "<person><name>Second Person Name</name></person>" + //
            "</people>" //
        ).getBytes()));

    String fragment = "<name>Changed Name</name>";
    Document fragmentDoc = builder.parse(new ByteArrayInputStream(fragment
        .getBytes()));

    Node injectedNode = doc.adoptNode(fragmentDoc.getFirstChild());

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("http://people/person[2]/name");
    Element nodeFound = (Element) expr.evaluate(doc, XPathConstants.NODE);

    Node parentNode = nodeFound.getParentNode();
    parentNode.removeChild(nodeFound);
    parentNode.appendChild(injectedNode);

    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(domSource, result);
    System.out.println(result.getWriter().toString());
  }
}