I'm trying to parse the following XML and create Java objects corresponding to the main elements:
<bookCase>
<material>wood</material>
<shelves>12</shelves>
...
<listOfBooks>
<book name="book1">
<author>someone</author>
<pages>200</pages>
...
</book>
<book name="book2">
<author>someone else</author>
<pages>500</pages>
...
</book>
</bookCase>
So I want to create Java objects BookCase, which contains a List of Book objects.
I'm trying to use AutoPilot with XPath, but although I can get to the main values (material="wood", shelves="12"), I don't know how to iterate through the listOfBooks and create the two Book objects. Any idea?
With the simple method below I can fetch the index of the two Book elements, but what do I with them?
private List<Integer> getBooksNodes() throws VTDException {
final String xpath = "/bookCase/listOfBooks/book";
ap.selectXPath(xpath);
final List<Integer> nodeList = new ArrayList<>();
int node;
while ((node = ap.evalXPath()) != -1) nodeList.add(node);
ap.resetXPath();
return nodeList;
}
How do I tell the AutoPilot to explore the values for the XPath "author" and "pages" for each book individually so I can create a Book object each time AutoPilot has finished exploring that section?
Ok, below is the code for exploring the author and pages nodes... I am not making the assumption that the book node must have author or pages nodes...
private List<Integer> getBooksNodes(VTDNav vn) throws VTDException {
final String xpath = "/bookCase/listOfBooks/book";
ap.selectXPath(xpath);
final List<Integer> nodeList = new ArrayList<>();
int node;
while ((node = ap.evalXPath()) != -1) {
nodeList.add(node);
// the logic that browses the pages and author nodes
// just print em out...
// remember vn is automatically moved to the xpath output by
// autoPilot
// we are gonna move the cursor manually now
if (vn.toElement(FIRST_CHILD,"author")){
int i = vn.getText();
if (i!=-1)
System.out.println(" author is ====>" + vn.toString(i));
vn.toElement(PARENT);
}
if (vn.toElement(FIRST_CHILD,"pages")){
int i = vn.getText();
if (i!=-1)
System.out.println(" author is ====>" + vn.toString(i));
vn.toElement(PARENT);
}
// also remember that in a xpath eval loop, if you are gonna
// move the cursor manually
// the node position going into the cursor logic must be identical
// to the node position existing the cursor logic
// an easy way to accomplish this is
// vn.push() ;
// your code that does manual node traversal
// vn.pop();
// but the logic above didn't use them
// because move cursor to child, then moving back, essentially move
// the cursor to the original position
}
ap.resetXPath();
return nodeList;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.