XML & XSD traversing with XPath and XmlDocument
Blog Date: 4/22/2008
XPath does not seem to function if you are searching for an element with a colon ":". In my case I am working with an XSD file with the element "xs:element".
I keep getting the error:
Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.
Well, it turns out you need an XmlNamespaceManager instance
// Load the Xml
string startNode = "Cars";
ClassObject newClass = null;
XmlDocument xDoc = new XmlDocument();
xDoc.Load(filename);
//Setting up NSManager
XmlNamespaceManager mgr = new XmlNamespaceManager(xDoc.NameTable);
mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
// Get first element and new up an object
// ... select elements which have a "name" attribute only
XmlNodeList xNodes = xDoc.SelectNodes(".//xs:element[@name]", mgr);
if (string.IsNullOrEmpty(startNode.Trim()))
startNode = xNodes[0].Attributes["name"].Value;
else
xNodes = xDoc.SelectNodes(
string.Format(".//xs:element[@name='{0}']//*", startNode), mgr);
Great article:
http://www.codeproject.com/KB/cpp/myXPath.aspx
4/22/2008 1:00:49 PM