在Java中使用Xpath更新Xml标记的值
我试图在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>
输入的用户值应仅重新写入第二个“版本”标记的值。请帮忙
# 1 楼答案
试试这个:
更新
为了使上述代码正常工作,必须使用以下导入: