xpath query with namespace

D

dc

i have a xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<validate xmlns="http://tempuri.org/fieldValidate.xsd">
<field name="Short Name" type="SN" length="10">
<requiredChar value="Y" errMsg="required Y" />
<requiredChar value="X" errMsg="required X" />
<bannedChar value="Z" errMsg="banned Z" />
<bannedChar value="A" errMsg="banned A" />
</field>
<field name="Name" type="N" length="250">
<requiredChar value="Y" errMsg="required Y" />
<requiredChar value="X" errMsg="required X" />
<bannedChar value="Z" errMsg="banned Z" />
<bannedChar value="A" errMsg="banned A" />
</field>
</validate>

And I want to get XmlElement of field which field type is SN. Then I used
this.xmlDoc.SelectSingleNode("//field[@type='SN']" );
But it fail to get the field element. Then I try to delete the
xmlns="http://tempuri.org/fieldValidate.xsd" in validate field, the code
works. After reading some doc, it said:
There is no namespace support for XPath queries specified directly in the
URL. If you want to use a namespace in an XPath query, template should be
used.
I am new in XML, I hope I havn't lead you to a wrong direction

Thanks!
 
S

SQL Server Development Team [MSFT]

You are almost there. Use SelectionNamespaces property to declare namespace
"a" and use "a:field"

Set o = CreateObject("MSXML2.DOMDocument.3.0")
o.async = false
o.load("my.xml")
o.setProperty "SelectionLanguage", "XPath"
o.setProperty "SelectionNamespaces",
"xmlns:a='http://tempuri.org/fieldValidate.xsd'"
WScript.echo o.selectSingleNode("//a:field[@type='SN']").xml

One word of caution though // is a big performance hit. I you use full path
you would get better perf out of your apps. So use

/a:validate/a:field[@type='SN']

as your xpath query.

Regards,
- Umut Alev
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top