Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change xml attribute value with XPath with vtd-xml Java

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"/>
like image 909
FDC Avatar asked Jun 03 '26 05:06

FDC


1 Answers

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.

like image 73
FDC Avatar answered Jun 05 '26 22:06

FDC