1
\$\begingroup\$

I have a structure like this:

<a>
 <b>
 <c>foo</c>
 <d>bar</d>
 </b>
 <b>
 <c>baz</c>
 <d>qux</d>
 </b>
</a>

I set /a/b as context and loop through all occurrences to get the texts of c and d:

VTDGen vg = new VTDGen();
vg.parseFile("test.xml", true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/a/b");
while(ap.evalXPath() != -1) {
 String c = extractText(vn, "c");
 String d = extractText(vn, "d");
}

Currently, I use the extractText() method I've written to extract the texts of the nodes inside the loop:

public String extractText(VTDNav v, String path) throws Exception {
 VTDNav vn = v.cloneNav();
 AutoPilot ap = new AutoPilot(vn);
 ap.selectXPath(path);
 int elementIndex = ap.evalXPath();
 if(elementIndex == -1) {
 return null;
 }
 int tokenIndex = (path.contains("@"))
 ? vn.getAttrVal(vn.toString(elementIndex))
 : vn.getText();
 return (tokenIndex == -1) ? null : vn.toString(tokenIndex);
}

In the method, I clone the VTDNav and create a new AutoPilot instance so I don't displace the cursor of those objects of my loop when selecting the new XPath.

Furthermore, I have to check the path whether it contains an @, to see if it's an text node or an attribute (i.e. to use getText() or getAttrVal()).

My profiler shows that my extractText() method takes the most time in my huge application, so there must be a better solution here.

asked Jan 15, 2015 at 9:08
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I've found a solution, which doesn't improve the performance, but is a lot shorter. I didn't know about the evalXPathToString() method.

protected String extractText(VTDNav v, String path) throws Exception {
 AutoPilot ap = new AutoPilot(v);
 ap.selectXPath(path);
 return ap.evalXPathToString();
}

Furthermore, the check in my old version whether the path contains a @ was buggy. It returned true for a path like /a[@b='c'] and executed getAttrVal() for it, which is wrong.

answered Feb 10, 2015 at 11:18
\$\endgroup\$
3
  • \$\begingroup\$ Did u put this function in a loop? \$\endgroup\$ Commented Feb 26, 2015 at 5:09
  • \$\begingroup\$ Yes, please take a look at my first code block in the question. I use this function within the while-loop. \$\endgroup\$ Commented Feb 26, 2015 at 8:20
  • \$\begingroup\$ Take xpath compilation out of loop especially when your XML is small. \$\endgroup\$ Commented Oct 20, 2015 at 5:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.