0

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

4
  • 1
    Its hard to help without knowing what you used for the variable xpath Commented Oct 31, 2014 at 8:23
  • I have made the changes according to what i'm using in the code. Commented Oct 31, 2014 at 9:45
  • xpathObj.evaluate(xpath, doc, XPathConstants.NODE); -- you haven't included the value of xpath anywhere in your question. Commented Oct 31, 2014 at 10:37
  • Your XML is not valid and you'll have an error when parsing it. To correct, close the <properties> tag with </properties>. Commented Oct 31, 2014 at 11:01

1 Answer 1

5

Try this:

try {

    // Create a document by parsing a XML file
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse(new File("C:/temp/test.xml"));

    // Get a node using XPath
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/project/version";
    Node node = (Node) xPath.evaluate(expression, document, XPathConstants.NODE);

    // Set the node content
    node.setTextContent("Whatever I want to write");

    // Write changes to a file
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.transform(new DOMSource(document), new StreamResult(new File("C:/temp/test-updated.xml")));

} catch (Exception e) {
    // Handle exception
}

Update

In order to the above code work, you must use the following imports:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
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.Node;
Sign up to request clarification or add additional context in comments.

6 Comments

The above code will edit the values of both the version tags but i want to change the value of the second "version" tag only..
@Lucy, Try now. I replaced /project/parent/version with /project/version.
Can you please put your code in try catch block..the above code is throwing a lot of exceptions..
When I'm using your code i get 2 errors.On the 3rd line it says "Cast..parse(..) to document" and on the last line of code it says "Cast..document to node"..Why is this happening??
@Lucy, please, show me the stacktrace. I have tested the code before posting and worked like a charm.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.