Search code examples
c#xpathxml-namespaceslinq-to-xmlxelement

Why can I not use an XPath on XML data with namespace?


I'm using the following code:

            string testingXML = "<Policy><Activity xmlns=\"http://schemas.microsoft.com/netfx/2009/xaml/activities\"></Activity></Policy>";

            var xmlReader = XmlReader.Create( new StringReader(testingXML) );
            var myXDocument = XDocument.Load( xmlReader );
            var namespaceManager = new XmlNamespaceManager( xmlReader.NameTable );
            namespaceManager.AddNamespace("", "http://schemas.microsoft.com/netfx/2009/xaml/activities");

            var result = myXDocument.XPathSelectElement(
                "/Policy/Activity",
                namespaceManager
            );

            var result2 = myXDocument.XPathSelectElement(
                "/Policy",
                namespaceManager
            );

And attempting to use a namespaceManager as to my understanding that should help resolve my issue. However, if I run the code above, the result variable comes back as null (result2 does come back as an XElement).

Should this not work? Am I setting the namespace incorrectly?


Solution

  • You must always use an explicit prefix in XPaths referencing nodes in a namespace diffrent from the null one - i.e.:

            namespaceManager.AddNamespace("msact", "http://schemas.microsoft.com/netfx/2009/xaml/activities");
    
            var result = myXDocument.XPathSelectElement(
                "/Policy/msact:Activity",
                namespaceManager
            );
    

    This is the way XPath works by design - it is not related to the specific implementation.