Job Search
  |  Blog
  |  Contact
  |  Site Map
  |  Home
  |  

XML & XSD traversing with XPath and XmlDocument

Blog Date: 4/22/2008

Recent Blogs

<< Back

Visual Studio 2008 and Unit Testing 3/19/2008

Working on a new site 4/8/2008

Visual Studio 2008 : Get latest does not work in TFS 4/18/2008

 More Blogs...
 

IT Jobs Hiring


Business Intelligence Programmer Analyst North Chicago, IL

.NET Developer - PROVEN, Inc. San Diego, CA

More jobs...
 

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