Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do type-safe Xpath queries in Java?

I'm currently using JDOM for doing some simple XML parsing, and it seems like nothing's type safe - I had a similar issue with using the built-in Java DOM parser, just with lots more API to wade through.

For example, XPath.selectNodes takes an Object as its argument and returns a raw list, which just feels a little Java 1.1

Are there generic-ized XML and XPath libraries for Java, or is there some reason why it's just not possible to do XPath queries in a type-safe way?

like image 279
decitrig Avatar asked Nov 06 '22 08:11

decitrig


1 Answers

If you're familiar with CSS selectors on HTML, it may be good to know that Jsoup supports XML as well.


Update: OK, that was given the downvote apparently a very controversial answer. It may however end up to be easier and less verbose than Xpath when all you want is to select node values. The Jsoup API is namely very slick. Let's give a bit more concrete example. Assuming that you have a XML file which look like this:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
        <name>John Doe</name>
        <age>30</age>
        <address>
            <street>Main street 1</street>
            <city>Los Angeles</city>
        </address>
    </person>
    <person id="2">
        <name>Jane Doe</name>
        <age>40</age>
        <address>
            <street>Park Avenue 1</street>
            <city>New York</city>
        </address>
    </person>
</persons>

Then you can traverse it like follows:

Document document = Jsoup.parse(new File("/persons.xml"), "UTF-8");

Element person2 = document.select("person[id=2]").first();
System.out.println(person2.select("name").text());

Elements streets = document.select("street");
for (Element street : streets) {
    System.out.println(street.text());
}

which outputs

Jane Doe
Main street 1
Park Avenue 1

Update 2: since Jsoup 1.6.2 which was released March 2012, XML parsing is officially supported by the Jsoup API.

like image 74
BalusC Avatar answered Nov 09 '22 02:11

BalusC