Search code examples
xquerysaxon

How to validate the ContextItem in xquery


My XSLT is primitive, my XQuery almost non existent, this should be trivial, so I wont post a whole example.

I have an XQuery, that I'm compiling and executing via the dotnet saxon9ee-api

import schema default element namespace "" at "MessingAbout.xsd";

for $v in (validate { doc("MessingAbout.xml") })/element(SQUARE,FILLEDSQUARETYPE)
return <OUTPUT>{$v/@colour}</OUTPUT>

which works very nicely.

I want to use the "ContextItem" though, so I can query different XMLS, and I've got this to work, by setting the ContextItem in the XQueryEvaluator to a document.

import schema default element namespace "" at "MessingAbout.xsd";

for $v in /SQUARE
return <OUTPUT>{$v/@colour}</OUTPUT>

but I'd like to validate the contextItem and then use that do use things like element(SQUARE,FILLEDSQUARETYPE)...but how do you do this?


Solution

  • I'm not quite sure what you're attempting to do, but given "MessingAbout.xsd":

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               elementFormDefault="qualified">
      <xs:complexType name="FILLEDSQUARETYPE">
        <xs:attribute name="colour" type="xs:string"/>
      </xs:complexType>
    
      <xs:element name="SQUARE" type="FILLEDSQUARETYPE"/>
    </xs:schema>
    

    and "MessingAbout.xml":

    <SQUARE colour="red"/>
    

    your first query produces <OUTPUT colour="red"/>, which I assume is what you expect. To use the context item in the second query, I rewrote it as:

    import schema default element namespace "" at "MessingAbout.xsd";
    
    for $v in (validate { . })/element(SQUARE,FILLEDSQUARETYPE)
    return <OUTPUT>{$v/@colour}</OUTPUT>
    

    and passed the source document on the command line: -q:test2.xq -s:MessingAbout.xml.

    That gives me the same result as the first query. I hope that's helpful.