0

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?

Kyle
  • 17,317
  • 32
  • 140
  • 246
  • 1
    Side note: Policy and Activity have different namespaces, so there is no way to specify single namespace prefix for both as you are trying to do in `/Policy/Activity` (you trying empty namespace prefix for both, which is in XPath *always* mapped to empty namespace - see MiMo +1 answer). – Alexei Levenkov Feb 20 '13 at 19:35

2 Answers2

2

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.

MiMo
  • 11,793
  • 1
  • 33
  • 48
  • Thanks. From what I had read I thought I was using a default namespace and did not realize I needed to specify the prefix. – Kyle Feb 20 '13 at 19:35
0

You are mixing XmlReader with Linq2xml

In Linq2xml it should be

XDocument doc=XDocument.Parse(testingXML);
XNamespace ns="http://schemas.microsoft.com/netfx/2009/xaml/activities";
doc.Element(ns+"Activity");
Anirudha
  • 32,393
  • 7
  • 68
  • 89