0
votes

I have an XQuery query where I create an XHTML document out of data stored in XML. The XML looks like this:

<document>
    <div>
        <head>name-I-should-display</head>
        <!-- more data -->
    </div>
    <div>
        <head>name-of-div-2</head>
        <!-- more data -->
    </div>
    <!-- more divs -->
</document>

In my xquery, I can retrieve the XML document fine:

let $mydoc := doc("my-xml-file.xml")

I can get the "document" node like this:

let $rootnode := $mydoc/*[1]

but if I try this:

let $rootnode := $mydoc/document

I get nothing. When I get the "document" node with the first form, the divs behave the same way. I'm very new to XQuery but I know this should work as it already had in another query on a document with a very similar structure.

Additional information that could help:

  • used program is BaseX 9.0.2 on linux
  • I'm using the /name() function to determine whether or not I have retrieved the node I wanted to or retrieved null
  • the XML file has an XSLT stylesheet declaration at the beginning, the similar file that had worked this way didn't have one
  • I cannot modify the XML file

What could have gone wrong?

1
Did you try let $rootnode := $mydoc/*[name()='document']?Andersson
And if that doesn't work, try let $rootnode := $mydoc/*[local-name()='document']. If that works (and name() doesn't), you most likely have a default namespace you're not showing in your example.Daniel Haley

1 Answers

2
votes

Is the XML document also an XHTML document in the XHTML namespace? If so, then your XPath is failing because it only selects elements without a namespace. Try:

let $rootnode := $mydoc/*:document

The asterisk in this instance wildcards the namespace, but not the element name. If that selects the root, then the element is in a namespace. You can discover the URI of the namespace using this:

fn:namespace-uri-from-QName($mydoc/*/fn:node-name(.))

Then you can take that value and assign it to a prefix in the prolog of your XQuery (This example assumes the output is the XHTML namespace):

declare namespace xh="http://www.w3.org/1999/html";

Using the prefix, you can select the elements you want using XPath more specifically:

let $rootnode := $mydoc/xh:document