Xml Schema Validation and XPath Query

I've recently begun using an XML file as a source of  “instructions” for an installation program I'm building.  Given that I'll be killing and rebuilding database objects, directories, files, etc., I need to be sure that the XML file fits a certain schema before I do anything.  No problem--in the VS .NET IDE, right-click and select Create Schema.  So far so good. 

Validation of the Schema is fairly simple using the XMLValidatingReader.  Again no problem.

Now I need to use XPath queries to get to various nodes in the document--problem.

When the document has a default namespace (in this case created by the VS .NET IDE), XPath queries fail. There is a workaround, and it's not very hard.  Here are my comments from my code:

'

' Essentially, the issue boils down as follows:

' In order to validate the document against a schema, the document must contain a namespace.

' The VS .NET IDE automatically provides "http://tempuri.org/<<Xml File Name>>.xsd" as a default

' namespace. This is great because it makes validation a fairly simple process.

' The gotcha in all this is that the default namespace renders XPath Querying of the

' DOM nearly impossible. Since the nodes are in a namespace, XPath requires that you

' prefix the nodes you're interested in via the namespace prefix--but since this is the

' default namespace, there is no namespace prefix.

' Ths solution is to provide a namespace prefix via the XmlNameSpaceManger.

'

' This article wasn't very useful in this specific context, but it did contain some useful

' information regarding the XML specification. In short it provides the theoretical overview

' as to why this is a problem in the first place, and shows that future revisions of the

' XML specification may be more intuitive on this issue.

' http://www.topxml.com/people/bosley/defaultns.asp

'

' This article provides the specific solution to my specific problem. It shows how to work

' around the default namespace without removing it, thereby retaining the ability to validate

' the document, and the ability to query the document.

' http://weblogs.asp.net/wallen/archive/2003/04/02/4725.aspx

'

I'm sure I'll need to refer back to this code in the future, so I'll leave it here on my blog for everyone's benefit.

Chris

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)