【发布时间】:2014-01-07 11:18:21
【问题描述】:
当我使用以下代码修改 xml 文件时,我收到此错误:
Exception in thread "main" java.lang.NullPointerException
at ModifyXMLFile.updateFile(ModifyXMLFile.java:44)
at ModifyXMLFile.main(ModifyXMLFile.java:56)
错误发生在以下行:node.setTextContent(newValue);
我没有正确使用 xpath 吗?
这是我正在尝试更新的代码和 xml 文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class ModifyXMLFile {
public void updateFile(String newValue){
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
try {
File f = new File("C:\\pom.xml");
InputStream in = new FileInputStream(f);
InputSource source = new InputSource(in);
Node node = (Node)xpath.evaluate("/project/parent/version/text()", source, XPathConstants.NODE);
node.setTextContent(newValue);
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String argv[]) {
new ModifyXMLFile().updateFile("TEST");
}
}
xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>testgroup</groupId>
<artifactId>testartifact</artifactId>
<version>update</version>
</parent>
</project>
【问题讨论】: