【发布时间】:2014-10-31 08:07:13
【问题描述】:
我正在尝试使用 Java 中的 XPath 更改 XML 文件的特定标记的值。我正在尝试使用 XpathFactory 来实现这一点,但无法做到。如果有更好的方法,请纠正我。
JAVA 代码..
public class MavenMetadataReader {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws XMLStreamException {
Scanner user_input = new Scanner( System.in );
String updated_pom_version;
System.out.println("Enter updated version:");
updated_pom_version = user_input.next( );
File xpath=new File("D:\\Lucy\\trunk\\pom.xml");
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpathObj = xfactory.newXPath();
Node node;
try {
node = (Node)xpathObj.evaluate(xpath, doc, XPathConstants.NODE);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
node.setTextContent(elementValue);
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>com.avocent</groupId>
<artifactId>common-configurations</artifactId>
<version>0.0.4</version>
</parent>
<groupId>com.avocent.commonplatform.cps.symbols</groupId>
<artifactId>GDDResources</artifactId>
<version>4.0.0.129-SNAPSHOT</version>
<description>Resources for init data strings</description>
<packaging>jar</packaging>
<properties>
<src>${basedir}</src>
<dst>${basedir}/target/classes</dst>
</properties>
</project>
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>com.avocent</groupId>
<artifactId>common-configurations</artifactId>
<version>0.0.4</version>
</parent>
<groupId>com.avocent.commonplatform.cps.symbols</groupId>
<artifactId>GDDResources</artifactId>
<version>3.6.10</version> **<-- Changes are to be made in second version tag, not the first**
<description>Resources for init data strings</description>
<packaging>jar</packaging>
<properties>
<src>${basedir}</src>
<dst>${basedir}/target/classes</dst>
</properties>
</project>
输入的用户值应该只重写第二个“版本”标签的值。请帮助
【问题讨论】:
-
如果不知道您对变量
xpath使用了什么,这很难提供帮助 -
我已根据我在代码中使用的内容进行了更改。
-
xpathObj.evaluate(xpath, doc, XPathConstants.NODE);-- 您没有在问题的任何地方包含xpath的值。 -
您的 XML 无效,解析时会出错。要更正,请使用
</properties>关闭<properties>标记。
标签: java xml xpath xml-parsing