Reputation: 317
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"/>
Upvotes: 3
Views: 581
Reputation: 3377
Your xpath should be /task/trigger/@count
the statement for change attr value is xmlModifier.updateToken(i+1)
Below is a sample without resorting to namespaces...
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import com.ximpleware.*;
public class updateAttrVal2 {
public static void main(String[] s) throws VTDException,UnsupportedEncodingException,IOException{
VTDGen vg = new VTDGen();
String xml="<task xmlns='ns1' xmlns:abc='ns2'><abc:trigger count=\"myCount\" interval=\"myInterval\"/></task>";
vg.setDoc(xml.getBytes());
vg.parse(false);
VTDNav vn=vg.getNav();
AutoPilot ap = new AutoPilot(vn);
XMLModifier xm = new XMLModifier(vn);
ap.selectXPath("/task/trigger/@count");
int i=0;
while((i=ap.evalXPath())!=-1){
xm.updateToken(i+1, "Count");
}
XMLByteOutputStream xms = new XMLByteOutputStream(xm.getUpdatedDocumentSize());
xm.output(xms);
System.out.println(xms.toString());
}
}
Upvotes: 0
Reputation: 317
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.
Upvotes: 2