我从这里开始考虑一个例子:http://www.rgagnon.com/javadetails/java-0625.html
我们有一个XML文件:
<data>
<employee>
<name>John</name>
<title>Manager</title>
</employee>
<employee>
<name>Sara</name>
<title>Clerk</title>
</employee>
</data>
我们使用这个Java应用程序:
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)));
}
}
将<name>John</name>
更改为<name>John Paul</name>
。
该示例适用于拉丁符号,数字,标点符号,但如果我尝试将原始值替换为用西里尔符号编写的原始值,则会返回一堆不可读的字符。
所以问题是:有没有办法修改Java代码以使其按照我需要的方式工作?
我是Java的新手。