views:

60

answers:

2

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?

A: 

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 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
BalusC
I think that may be what I'm looking for - looks like it's not as strict as JDOM (no validation), but I like the simple API.
slide_rule
You're welcome.
BalusC
A: 

AFAIK all of the xml queries in java are non-typesafe and most are java 1.3 compatible. That said my favorite parser/generator is the xml pull parser (xmlpp) style parser. I believe java has XmlStreamReader and XmlStreamWriter if you're using 1.6 which are almost the same as the xmlpp library. I especially like that I can write a method getFoo that takes a stream reader and pulls from it and returns a Foo object. It's sort of the best between DOM and SAX. I think it may be referred to as StAX by some.
I'm getting a little ramble-y so I'm quitting now

KitsuneYMG
That's interesting, but the whole point is that I don't want to write a whole parser - I just want the information out of the XML file with a minimum of syntax.
slide_rule