简体   繁体   中英

Update value of Xml tag using Xpath in Java

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM