我正在尝试解析以下XML并创建与主要元素相对应的Java对象:
<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>所以我想创建BookCase对象,它包含一个Book对象列表。
我正在尝试将AutoPilot与XPath一起使用,但是尽管我可以获得主值(material=“material=”,shelves="12"),但我不知道如何遍历listOfBooks并创建两个Book对象。有什么想法吗?
使用下面这个简单的方法,我可以获取两个Book元素的索引,但是我该如何处理它们呢?
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;
}如何告诉AutoPilot分别为每本书探索XPath "author“和"pages”的值,以便每次AutoPilot浏览完该节后都能创建一个book对象?
发布于 2016-01-26 07:26:08
好的,下面是浏览author和pages节点的代码……我并没有假设图书节点必须有author或pages节点……
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;
}https://stackoverflow.com/questions/34994819
复制相似问题