user3088554
user3088554

Reputation: 31

xquery not working on a valid xml instance

This is my company.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="company.xsl"?>
<Company xsi:schemaLocation="http://localhost company.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://localhost">
<!--the Department Part-->
<Department>
    <deptId>ADM</deptId>
    <deptName>Admin</deptName>
    <deptAddr>LA</deptAddr>
</Department>

<Department>
    <deptId>FIN</deptId>
    <deptName>Finance</deptName>
    <deptAddr>LA</deptAddr>
</Department>
</Company>

And this is my company.xsd file

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  targetNamespace="http://localhost"   
  xmlns="http://localhost" 
  elementFormDefault="qualified">
 .........
</xsd:schema>

This is my q1.xquery file:

xquery version "1.0";
<query1>
{
for $x in doc("company.xml")//Company//Department
return <result><deptId>{data($x//deptId)}</deptId><deptName>{data($x//deptName)}</deptName>   </result>

}
</query1>

if I keep all three files like this, the xquery wont work, however, if I remove the namespace declaration part in the company.xml, the xquery will work. It seems that the xquery has something to do with the namespace. Can someone help me with this issue? and by the way, the xml file is a valid instance of that xml schema. I have tried different ways but none of them work..

Upvotes: 1

Views: 688

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122384

It seems that the xquery has something to do with the namespace.

Yes. To match namespaced nodes you need to declare the namespace in your query

xquery version "1.0";
declare namespace co = "http://localhost";
<query1>
{
for $x in
doc("company.xml")//co:Company//co:Department
return .....

If you have no need to refer to non-namespaced elements in your query then instead of declaring a prefix, it is possible to

declare default element namespace "http://localhost";

Upvotes: 4

Related Questions