Monday, April 25, 2011

Mapping XPath 1.0 data types to java

I'm using XPath 1.0 to process incoming web services messages. This can be quite hard to get right if schema data types are used, because XPath 1.0 does not recognize them (XPath 2.0 does, but there seems to be no full open source implementation. Not sure if Saxon-B does this).

E.g., the literals "true" and "false" in a xs:boolean represent the boolean values True and False according to xml schema, but XPath 1.0 will evaluate both of them to True.

This means that evaluating /test against <test>false</test> actually returns True.

The same goes for other datatypes as well: "12.78e-2" is a valid value for xs:double, but evaluates to Double.NaN.

javax.xml.datatype contains type mappings for duration and dateTime, but that's it.

XMLBeans contains easy to use converters between java and schema's built-in data types:

Node n = jaxp13XPathTemplate.evaluateAsNode(expression, context);
boolean b = XmlBoolean.Factory.parse(n).getBooleanValue();

Are there any other tools that might be helpful (and no, I'm not looking for a full-fledged XML binding framework)?

From stackoverflow
  • Hi There,

    I know you said you don't want a fully fledged binding framework but have you looked at jibx. It can be a bit of a pain to write the binding files however you can generate the bindings from an XML schema is you have one and its so quick its untrue.

    As an alternative to using XPath have you considered parsing the xml into a dom which you could then manipulate?


    sapporo : Karl, I haven't looked at JiBX closely so far. I'd rather avoid the byte code enhancement stuff if possible. Can you elaborate about your DOM idea? What exactly would I gain by having a DOM? Anyway, thanks for your input!
    Karl : If you want to process incoming XML its always preferable to get the XML into some type safe format normally an object to help simplify processing. DOM's are not type safe but depending on how complicated your xpath is you may find it easier to extract and manipulate the data:
    sapporo : I know about JDOM and friends, but I'm using XPath for a reason. That's why I asked about "Mapping XPath 1.0 data types to java" specifically, and not about XML processing in general.


Post a Comment