Change xml attribute value with XPath with vtd-xml Java

Question

I have to set the value of "count" attribute in this xml:

<?xml version="1.0" encoding="UTF-8"?>
<task>
   <trigger count="myCount" interval="myInterval"/>
   <property name="myName" value="myValue"/>
   <property name="mySecondName"value="mySecondValue">
</task>

i'd like to change myCount value with "Foo" with a code like this (VTDXML library):

            String count  = "Foo";
            if (vg.parseFile("C:\\Users\\_myPath_\\myFile.xml", true)) {
                VTDNav vn = vg.getNav();
                ap.bind(vn);
                xm.bind(vn);
                ap.selectXPath("/*[name()='task']/*[name()='trigger']");
                int i=0;
                while((i=ap.evalXPath())!=-1){
                    xm.insertAfterHead(count);
                }
                xm.output("C:\\Users\\_myPath_\\myFileWithFoo.xml");
                System.out.println(vg);
            }

In this way i obtain instead

  <trigger count="myCount" interval="myInterval">Foo</trigger>

that is not my goal, because what i want is

  <trigger count="Foo" interval="myInterval"/>

Show source
| java   | xml   | parsing   | xpath   | vtd-xml   2017-01-04 09:01 2 Answers

Answers ( 2 )

  1. 2017-01-04 13:01

    I found this solution applied for changing the content of both "count" and "interval":

               String count= "Foo";
               String interval= "Dummy";       
               String attribute  = " count=\""+ foo + "\" interval=\""+ interval+"\"";
                if (vg.parseFile("C:\\Users\\_myPath_\\myFile.xml", true)) {
                    VTDNav vn = vg.getNav();
                    ap.bind(vn);
                    xm.bind(vn);
                    ap.selectXPath("/*[name()='task']/*[name()='trigger']");
                    int i=0;
                    while((i=ap.evalXPath())!=-1){
                        xm.insertAttribute(attribute);
                    }
                    xm.output("C:\\Users\\_myPath_\\myFileWithFoo.xml");
                    System.out.println(vg+attribute);
                }
    

    And the result is:

     <trigger count="Foo" interval="Dummy" />
    

    I used method insertAttribute that appends my string to the name of the node (trigger).

    I know this is an horrible solution, but it works fine.

  2. 2017-01-05 00:01

    Your xpath should be /task/trigger/@count

    the statement for change attr value is xmlModifier.updateToken(i+1)

◀ Go back