简体   繁体   English

在JSoup中获取基于父元素的元素

[英]Get element based on parent in JSoup

In the following XML I'd like to be able to get the content of the first title tag and not the second. 在下面的XML中,我希望能够获得第一个标题标记的内容,而不是第二个。 Unfortunately the code prints the content of both title tags... 不幸的是,代码打印了两个标题标签的内容......

Any help would be great thanks! 任何帮助都会非常感谢!

String feedXMLString = "<entry><title>title 1</title><source><title>title 2</title></source></entry>";
    Document feedXML = Jsoup.parse(feedXMLString);

    NodeTraversor feedXMLTraversor = new NodeTraversor(new NodeVisitor() {

          @Override
          public void tail(Node node, int depth) {
              if (node instanceof Element) {

                  String tagName = ((Element) node).tagName();                    
                  String parentTagName = ((Element) node).parent().tagName();

                  if (tagName.equals("title")) {          
                      if (parentTagName.equals("entry")) {
                          String title = ((Element) node).ownText();
                          System.out.println(title);
                      }
                  }
              }
          }

          @Override
          public void head(Node node, int depth) { 
          }
        });
    feedXMLTraversor.traverse(feedXML.body());

Output is 输出是

title 1
title 2

I just want it to be title 1. I'm working under the assumption that the parent tag of the second title is <source> , but for some reason JSoup seems to think that it is <entry> 我只是想让它成为标题1.我假设第二个标题的父标签是<source> ,但由于某种原因,JSoup似乎认为它是<entry>

Thanks! 谢谢!

Thanks! 谢谢!

Why don't you use the selector part of the Jsoup API? 为什么不使用Jsoup API的选择器部分? It's much much easier to use, it's cleaner, and I'm willing to bet that's faster as well. 它使用起来要容易得多,它更干净,而且我愿意打赌它也会更快。 What I'd personally use is this: 我个人使用的是:

//The line you already had
Document doc = Jsoup.parse(feedXMLString);

//This will get you all the titles
Elements elems = doc.select("title");

//And now you can proceed in various ways:
String title1stWay = elems.first().text();
String title2ndWay = elems.get(0).text();

Take a look here: Jsoup Selector API 看看这里: Jsoup Selector API

try adding (below String tagName ,String parentTagName... ) 尝试添加(在String tagName ,String parentTagName...下面String tagName ,String parentTagName...

int numOfParents = ((Element) node).parents().size();

and changing 和改变

if (parentTagName.equals("entry"))

into

if (parentTagName.equals("entry") && (numOfParents == 1))

?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM