Home > Software engineering >  SaxonHE: How to use XSD types on XQuery execution
SaxonHE: How to use XSD types on XQuery execution

Time:10-21

I have the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<root xsi:noNamespaceSchemaLocation="example.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <a>0.1</a>
    <b>0.2</b>
</root>

which is associated with the following XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="a" type="xs:decimal"/>
                <xs:element name="b" type="xs:decimal"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Using this code snippet I execute an XQuery expression let $a := /root/a, $b := /root/b, $res := $a $b return $res:

var proc = new Processor(false);

var builder = proc.newDocumentBuilder();
builder.setBaseURI(URI.create("http://test.ru"));

var file = new File(filePath);
var doc = builder.build(file);

var expression = "let $a := /root/a, $b := /root/b, $res := $a   $b return $res";

var compiler = proc.newXQueryCompiler();
var executable = compiler.compile(expression);
var selector = executable.load();
selector.setContextItem(doc);

return selector.evaluate();

The result is 0.30000000000000004. According this question (SaxonHE XQuery sum operation precision) it is because of the default number/xs:double type.

However, I have an XSD in which elements a and b have xs:decimal type. It there are any way to tell Saxon use types from XSD on XQuery expression executions?

CodePudding user response:

If you are able to switch to Saxon EE then you can of course use schema-aware XQuery with e.g. https://www.w3.org/TR/xquery-31/#id-schema-import and the schema will be used and your values will be xs:decimals. Or with the right settings the document might be parsed and validated based on the schemaLocation attribute (https://www.saxonica.com/html/documentation10/schema-processing/saqueryapi.html).

Even in HE, however, nothing prevents you from doing let $a := xs:decimal(/root/a), $b := xs:decimal(/root/b), you might need to declare the namespace in the query prolog.

  • Related