我试图解析以下XML并创建与主要元素对应的Java对象:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet" />
<input type="button" id="crit1" value="20%" />
<input type="button" id="crit2" value="40%" />
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Score</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
所以我想创建Java对象BookCase,它包含一个Book对象列表。
我试图将AutoPilot与XPath一起使用,但是虽然我可以使用主要值(材料=&#34; wood&#34;,shelf =&#34; 12&#34;),但我不知道#39;知道如何遍历listOfBooks并创建两个Book对象。有什么想法吗?
使用下面的简单方法,我可以获取两个Book元素的索引,但我对它们有什么看法?
<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>
如何告诉AutoPilot探索XPath&#34; author&#34;的值?和&#34;页面&#34;对于每本书,我都可以在每次AutoPilot探索该部分时创建一个Book对象吗?
答案 0 :(得分:0)
好的,下面是探索作者和页面节点的代码......我没假设书籍节点必须有作者或页面节点......
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;
}