I'm trying to change the value of a particular tag of a XML file using XPath in java. I'm trying to achieve this using XpathFactory but not being able to.Please correct me if there is a better way of doing this.
JAVA Code..
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);
The XML file..
<?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>
The Expected Changes in XML file.
<?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>
The entered user value should re-write only the value of the second "version" tag.Please Help
xpathxpathObj.evaluate(xpath, doc, XPathConstants.NODE);-- you haven't included the value ofxpathanywhere in your question.<properties>tag with</properties>.