首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >vtd-xml解析多次出现的元素

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

Stack Overflow用户
提问于 2016-01-25 22:19:33
回答 1查看 1.2K关注 0票数 1

我正在尝试解析以下XML并创建与主要元素相对应的Java对象:

代码语言:javascript
复制
<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元素的索引,但是我该如何处理它们呢?

代码语言:javascript
复制
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对象?

EN

回答 1

Stack Overflow用户

发布于 2016-01-26 07:26:08

好的,下面是浏览author和pages节点的代码……我并没有假设图书节点必须有author或pages节点……

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34994819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档