gpt4 book ai didi

java - vtd-xml 解析元素的多次出现

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:17 24 4
gpt4 key购买 nike

我正在尝试解析以下 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>

所以我想创建 Java 对象 BookCase,其中包含 Book 对象的列表。

我正在尝试将 AutoPilot 与 XPath 结合使用,但尽管我可以获取主要值(material=“wood”,shelf=“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“作者”和“页面”值,以便每次 AutoPilot 完成探索该部分时我都可以创建一个 Book 对象?

最佳答案

好的,下面是用于探索作者和页面节点的代码...我并没有假设书籍节点必须具有作者或页面节点...

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;
}

关于java - vtd-xml 解析元素的多次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34994819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com