Share via


Manage XPath namespaces programmatically in LINQ to XML

Want to use XPath with LINQ to XML on files with lots namespaces, like InfoPath forms?

This might help you :)

 // Add all namespaces on your document 

public static class MyExtensions
{
    public static XmlNamespaceManager CreateNamespaceManager(this XDocument doc)
    {
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.CreateReader().NameTable);
        
        foreach (XAttribute attr in doc.Root.Attributes())
        {
            if (attr.IsNamespaceDeclaration)
                nsmgr.AddNamespace(attr.Name.LocalName, attr.Value);
        }

        return nsmgr;
    }
} 

Then query your XDocument using the System.Xml.XPath extensions:

 XDocForm.XPathSelectElement("/my:Field1/my:Field2/my:Level1", XmlForm.CreateNamespaceManager());

Comments

  • Anonymous
    April 19, 2009
    PingBack from http://asp-net-hosting.simplynetdev.com/manage-xpath-namespaces-programmatically-in-linq-to-xml/

  • Anonymous
    June 11, 2009
    OK, but how can I use XPath queries when the XML uses a default namespace?  Your code results in an exception when it tries to add a namespace with the prefix "xmlns": Prefix "xmlns" is reserved for use by XML.  Even if I call AddNamespace with an empty string for the prefix (which seems to set the DefaultNamespace properly), XPath queries with no prefix fail to return any results.  Here's the beginning of my XML: <kml xmlns="http://earth.google.com/kml/2.2">  <Document>    <name>Gigapxl Photo Overlays</name> And I'm using an XPath query like "//name".  I'd rather not have to modify all my queries to include prefixes everywhere.