我得到以下代表新闻文章的XML:
<content>
Some text blalalala
<h2>Small subtitle</h2>
Some more text blbla
<ul class="list">
<li>List item 1</li>
<li>List item 2</li>
</ul>
<br />
Even more freakin text
</content>
Run Code Online (Sandbox Code Playgroud)
我知道格式不理想,但现在我必须接受它.
该条应如下:
我用Jsoup解析这个XML.我可以在<content>标签中获取文本,doc.ownText()但后来我不知道其他东西(副标题)放在哪里,我只有一个大String.
为此使用基于事件的解析器会更好(我讨厌它们:()还是有可能做类似的事情doc.getTextUntilTagAppears("tagName")?
编辑:为了澄清,我知道热门得到元素<content>,我的问题是获取文本<content>,每次被元素打断时分解.
我了解到我可以获取内容中的所有文本.textNodes(),效果很好,但是我再次知道文章节点在我的文章中的位置(一个位于h2之前的顶部,另一个位于底部).
Jsoup有一个出色的基于选择器的语法.看这里
如果你想要副标题
Document doc = Jsoup.parse("path-to-your-xml"); // get the document node
Run Code Online (Sandbox Code Playgroud)
你知道副标题在h2元素中
Element subtitle = doc.select("h2").first(); // first h2 element that appears
Run Code Online (Sandbox Code Playgroud)
如果您想要列表:
Elements listItems = doc.select("ul.list > li");
for(Element item: listItems)
System.out.println(item.text()); // print list's items one after another
Run Code Online (Sandbox Code Playgroud)