Change a particular node in XML

Consider this XML file.

<data>
 <employee>
    <name>John</name>
    <title>Manager</title>
 </employee>
 <employee>
    <name>Sara</name>
    <title>Clerk</title>
    </employee>
</data>

We want to change employee named “John” to “John Paul” You locate the element to change with an XPath query. You change the text and then save back the data.

import java.io.File;

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.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLReplaceDemo {
  static String inputFile = "C:/temp/data.xml";
  static String outputFile = "C:/temp/data_new.xml";

  public static void main(String[] args) throws Exception {
    Document doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new InputSource(inputFile));

    // locate the node(s)
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList)xpath.evaluate
        ("//employee/name[text()='John']", doc, XPathConstants.NODESET);

    // make the change
    for (int idx = 0; idx < nodes.getLength(); idx++) {
      nodes.item(idx).setTextContent("John Paul");
    }
 
    // save the result
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform
        (new DOMSource(doc), new StreamResult(new File(outputFile)));
  }
}

The result

<?xml version="1.0" encoding="UTF-8" standalone="no"?><data>
 <employee>
    <name>John Paul</name>
    <title>Manager</title>
 </employee>
 <employee>
    <name>Sara</name>
    <title>Clerk</title>
    </employee>
</data>

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部