如何使用 jsoup 解析 XML

2022-01-10 00:00:00 xml-parsing java jsoup

我正在尝试使用 jsoup 解析 XML,但我找不到有关此任务的任何示例.

I am trying to parse XML with jsoup, but I can't find any examples on this task.

我的 XML 文档如下所示:

<?xml version="1.0" encoding="UTF-8">
    <tests>
        <test>
            <id>xxx</id>
            <status>xxx</status>
        </test>
        <test>
            <id>xxx</id>
            <status>xxx</status>
        </test>
        ....
    </tests>
</xml>

应该很简单,但是我的尝试失败了.

It should be quite straightforward, but my attempt has failed.

代码:

Element content = doc.getElementById("content");
Elements tests = content.getElementsByTag("tests");
for (Element testElement : tests) {
    System.out.println(testElement.getElementsByTag("test"));
}

推荐答案

Jsoup 的最新版本(1.6.2 - 2012 年 3 月 28 日发布)似乎包含了对 XML 的一些基本支持.

It seems the latest version of Jsoup (1.6.2 - released March 28, 2012) includes some basic support for XML.

String html = "<?xml version="1.0" encoding="UTF-8"><tests><test><id>xxx</id><status>xxx</status></test><test><id>xxx</id><status>xxx</status></test></tests></xml>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
for (Element e : doc.select("test")) {
    System.out.println(e);
}

试一试..

相关文章