Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using xpath and vtd-xml to get sub nodes and text of an element as a string

This is a portion of my XML:

<MAIN>
    <L>
        <D>string1 string2 <b>string3</b> string4</D>
    </L>
    <L>
        <D>string5 string6 <b>string7</b> string8 <i>string9</i></D>
    </L>
</MAIN>

I want to get the content of all the <D> tags as string. So, the example above should return:

1st iteration: 'string1 string2 <b>string3</b> string4'
2nd iteration: 'string5 string6 <b>string7</b> string8 <i>string9</i>'
etc...

In vtd-xml I used an AutoPilot with XPath "//L/D" and "//L/D/text()" but that did not work.

Any advice or alternative approach will be appreciated.

Regards

like image 317
Alex Avatar asked May 14 '11 19:05

Alex


People also ask

What is XPath text in selenium?

Definition of XPath text XPath text () function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes.

How to find XML element with attribute value using XPath in Java?

Java example find xml element with attribute value using xpath Let’s look at the code which has been used to evaluate above xpath expressions to select nodes having certain attribute value. 2.1. XPath evaluate example Read XML file into org.w3c.dom.Document. Create XPathFactory with its newInstance () static method.

How do I find a specific node using XPath in HTML?

You can use XPath to find a single, specific node or to find all nodes that match some criteria. The DOM classes provide two methods for XPath selection: the SelectSingleNode method and the SelectNodes method.

What does the text () function do in XPath?

The text of the web element is used by the function to locate the element on the webpage. This function comes in handy if your element contains text, such as labels, which always have static text. The text () function in XPath has the following syntax:


1 Answers

Below is the code that does what you are looking for.

    VTDGen vg =  new VTDGen();
    if (vg.parseFile("c://xml//alex.txt", true)){
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("//L/D");
        int i=-1;
        while((i=ap.evalXPath())!=-1){
            long l = vn.getContentFragment();
            System.out.println(" -==> "+ vn.toString((int )l, (int)(l>>32)));
        }
    }
like image 103
vtd-xml-author Avatar answered Nov 14 '22 23:11

vtd-xml-author