Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse XML with jsoup

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

My XML document looks like this:

<?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.

Code:

Element content = doc.getElementById("content"); Elements tests = content.getElementsByTag("tests"); for (Element testElement : tests) {     System.out.println(testElement.getElementsByTag("test")); } 
like image 650
JavaCake Avatar asked Mar 27 '12 09:03

JavaCake


People also ask

Does jsoup work with XML?

But you can use it on XMLs as well and the good news is that they work just fine there. APIs present in Jsoup are easy to use. You can get the job done without having to write a colossal amount of code. Here's a step by step process on How to Read XML file in Java using Jsoup.

What is jsoup parse?

Description. The parse(String html) method parses the input HTML into a new Document. This document object can be used to traverse and get details of the html dom.

What is jsoup used for?

What It Is. jsoup can parse HTML files, input streams, URLs, or even strings. It eases data extraction from HTML by offering Document Object Model (DOM) traversal methods and CSS and jQuery-like selectors. jsoup can manipulate the content: the HTML element itself, its attributes, or its text.


1 Answers

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); } 

Give that a shot..

like image 130
B. Anderson Avatar answered Oct 06 '22 12:10

B. Anderson