Search code examples
javaxmlxsdvtd-xml

Using VTD-XML to modify element text only


I want to achieve below thing in vtd-xml xml modifier class.

Original xml 
<xml>
   <element attr1='1' attr2='2' attr3='3'>text</element>
</xml>

int p = vn.getText()
xm.updateToken(p, "new text");

But the code here is modifying the text to new text but it's not copying all the attributes. Any idea how to achieve this?

Other option is to call xm.remove() and then add tag. But, I don't know how to copy the attributes to new tag.

Thank you
Bala

Edit

testAP.selectXPath("pn[@category]");

while((j = testAP.evalXPath()) != -1)
{
     int p = vn.getText();
     xm.updateToken(p, "new text");
}

XML

<pn category = "ONE" GENERAL0 = "0" GENERAL1 = "-1" >previoustext</pn>

Above is the code.


Solution

  • I can't reproduce the problem... below I used the xml text in your example, the output I got is :

                     <pn category="ONE" GENERAL0="0" GENERAL1="-1" >new text</pn>
    

    Below is the test code I used

            String s = "<pn category=\"ONE\" GENERAL0=\"0\" GENERAL1=\"-1\" >previoustext</pn>";
            vg.setDoc(s.getBytes());
            vg.parse(true);
            vn = vg.getNav();
            AutoPilot testAP = new AutoPilot(vn);
            testAP.selectXPath("/pn[@category]"); 
            xm.bind(vn);
            int j; 
            while((j = testAP.evalXPath()) != -1) 
            { 
                 int p = vn.getText(); 
                 xm.updateToken(p, "new text"); 
            } 
            XMLByteOutputStream xbos =new XMLByteOutputStream(xm.getUpdatedDocumentSize());
            xm.output(xbos);
            System.out.println(new String(xbos.getXML()));
    

    Did you use the latest version of vtd-xml?