简体   繁体   中英

Edit general node in an XML file using xpath in Java

I need to edit general node in a XML file using xpath in Java. I have tried many different methods and approaches, and yet succeeded to complete this task successfully. Please assist, the problematic part mentioned in the code below.

Example for xml file i use:

 <data-source> <account-id>1102</account-id> <type>ftp</type> <url>http://abcom</url> <port>21</port> <username>user</username> <password>12345678</password> <update-frequency>1200</update-frequency> </data-source>

My function is as follows and the arguments:

 * Usage example: updateElementValue(FILE_LOCATION + "addDataSource.xml", "/data-source", "port", "80")
 * @param fileNameToUpdate - full file name (path + file name) to update
 * @param xpath - element node xpath
 * @param elementName - element name
 * @param elementValue - value to set  

  public static void updateElementValue(String fileNameToUpdate, String xpath, String elementName, String elementValue) throws Exception
      {
        // Exit with exception in case value is null
        if(elementValue == null) {
            throw new Exception("Update element Value function, elementValue to set is null");
        }

        //Read the file as doc  
        File fileToUpdate = new File(fileNameToUpdate);
        Document doc = FileUtils.readDocumentFromFile(fileToUpdate);


        //WHAT SHOULD I DO HERE?...


        //Save the doc back to the file
        FileUtil.saveDocumentToFile(doc, fileNameToUpdate);         
    }

If I understand correctly, you wont need elementName , as the XPath should identify a node uniquely. Use the javax.xml.xpath package...

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);

I haven't tried running your code exactly, but it should work.

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