java - 如何使用 Jsoup 遍历 XML 标签?

标签 java android xml xml-parsing jsoup

目前我有以下 XML 是这样的:

<item>
   <title> this is title 1 </title>
   <description> description 1 </description>
   <pubDate> date 1 </pubDate>
</item>

<item>
   <title> this is title 2 </title>
   <description> description 2 </description>
   <pubDate> date 2 </pubDate>
</item>

我正在使用 jsoup 但我得到的结果是:

this is title 1
this is title 2
description 1
description 2
date 1
date 2

我想要的实际结果:

this is title 1
description 1
date 1
this is title 2
description 2
date 2

我仍然是 android 的初学者。我想使用 Jsoup 来实现这一点。一个简单的示例代码会很有帮助。谢谢。

最佳答案

这是打印 item 元素的所有子元素的 fragment :

public class Test {

    public static void main(String[] args) {
        String xml = 
                "<item>\r\n" + 
                "   <title> this is title 1 </title>\r\n" + 
                "   <description> description 1 </description>\r\n" + 
                "   <pubDate> date 1 </pubDate>\r\n" + 
                "</item>\r\n" + 
                "\r\n" + 
                "<item>\r\n" + 
                "   <title> this is title 2 </title>\r\n" + 
                "   <description> description 2 </description>\r\n" + 
                "   <pubDate> date 2 </pubDate>\r\n" + 
                "</item>";

        Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
        for (Element item : doc.select("item")) {
            Elements children = item.children();
            for (Element child : children) {
                System.out.println(child.text());
            }
        }
    }
}

这是输出:

this is title 1
description 1
date 1
this is title 2
description 2
date 2

关于java - 如何使用 Jsoup 遍历 XML 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39225414/

相关文章:

java - 将 PHP 前端连接到后端 java 服务

java - 文件未完全写入

android - 使用 USB 主机 Api 在两部安卓手机之间传输数据

c# - XmlDocument.LoadXml 和 XDocument.Parse 之间的不同行为

java - 如何使用Java修改XML文件中的属性值

Java android,从图库获取图像并将其显示在屏幕上(错误)

java - 引用 Dalvik 或 Java 虚拟机?

java - 在 ArrayAdapter 中使网络调用安全吗?

android - firestore 内部断言失败

javascript - jquery ajax 调用强制响应中的 XML 元素名称为小写