Extract data from a namespaced XML file
Problem
You have an XML file on disk, and it uses XML namespaces. You want to load it with jsoup, select namespaced elements, and resolve relative URLs in the file.
Solution
Use a file parse method and pass Parser.xmlParser( explicitly.
A good real-world example is the package document from an EPUB. An EPUB file is a zip archive; inside it, the package document is XML and usually has a path like OEBPS/content.opf. It describes the book’s metadata, files, and reading order.
<package xmlns="http://www.idpf.org/2007/opf"
xmlns:dc="http://purl.org/dc/elements/1.1/"
version="3.0">
<metadata>
<dc:title>Practical Parsing</dc:title>
<dc:creator>Alex Reyes</dc:creator>
</metadata>
<manifest>
<item id="chapter1" href="chapters/ch01.xhtml"
media-type="application/xhtml+xml" />
</manifest>
<spine>
<itemref idref="chapter1" />
</spine>
</package>
Load the XML file, then read the metadata and follow the spine into the manifest:
Path opf = Paths.get("/books/practical-parsing/OEBPS/content.opf");
Document doc = Jsoup.parse(opf, null, opf.toUri().toString(), Parser.xmlParser());
Element metadata = doc.expectFirst("metadata");
String title = metadata.expectFirst("dc|title").text();
String creator = metadata.expectFirst("dc|creator").text();
System.out.println(title + " by " + creator);
for (Element itemref : doc.select("spine > itemref")) {
String idref = itemref.attr("idref");
Element item = doc.expectFirst("manifest > item#" + idref);
System.out.println(item.attr("abs:href"));
}
Description
For local files, there is no HTTP content type for jsoup to inspect, so pass Parser.xmlParser( to parse the input as XML. Passing the file URI as the baseUri lets jsoup resolve the package document’s relative href attributes with abs:href.
Namespace-prefixed elements can be selected with the prefix|name syntax. For example, dc|title selects <dc:title>, and dc|creator selects <dc:creator>. Use *|title if you want to match a tag by local name in any namespace.
The XML parser does not apply HTML tree rules. It preserves tag and attribute case, keeps XML declarations, and uses XML output settings. That makes it a good fit for extracting and updating XML documents.
jsoup is not validating the EPUB here. It is reading the XML tree and giving you the same DOM, selector, attribute, and URL tools that you use with HTML.