Wednesday, June 21, 2006

XML Namespace fun

What seemed like a steep mysterious challenge turned into a moldable, layered problem with many partial and a few complete easy solutions. I wrote some code to parse values out of and into elements of an XML document adhering to a schema. Very good, until I learn that schema can change infinitely. So I needed what I called an "agnotistic parser", a way to read and write the document without worrying about the namespace. Microsoft provides a NamespaceManager object in .Net for allowing you to run XPath statements against an XML document having schema information included.

So the only solution so I thought was to figure out how to tell the NamespaceManager what to use for the prefix used on the XML nodes.

It turns out one answer is to not attach a namespace manager and XPath as in :
*[local-name() = 'the-element-name-here']

from "Martin Honnen --- MVP XML".

More interesting to me is the looping over namespaces and adding them as found in microsoft.public.dotnet.xml :

foreach (XmlAttribute att in
Document.DocumentElement.Attributes)
if (att.LocalName == "ns1")
xmlNSMgr.AddNamespace(att.LocalName,
att.Value);

But this requires hard-coding the LocalName to be used in XPath queries.

The best answer I think is what my boss suggested. Get the defaults from the Root node of the doc as in:

xmlDoc.DocumentElement.Prefix;
xmlDoc.DocumentElement.Attributes["xmlns:" + xPathPrefix].Value;


And then add them to the Namespace Manager.

No comments: