-1

I have an XML returned from a REST call and I need to use xdoc.SelectNodes, however the XML has a namespace.

Sample XML

<SubscriptionOperationCollection xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <SubscriptionOperations>
        <subscriptionOperation>...</SubscriptionOperation>
    </SubscriptionOperations>

Question: Is there any way to use selectNodes() without specifying the namespace? My hesitation is in case the namespaces change in the future.

C#

// This returns 0, should return 1
xdoc.SelectNodes("/SubscriptionOperationCollection/SubscriptionOperations").Count;
doppelgreener
  • 4,809
  • 10
  • 46
  • 63
andrewb
  • 2,995
  • 7
  • 54
  • 95
  • 1
    instead of avoiding the namespace (which is not possible, I would say), you could get it from your xml document and set it as a variable (so you wouldn't mind any change) : see http://stackoverflow.com/questions/8241843/get-namespace-from-xml-file-c-sharp – Raphaël Althaus Sep 02 '13 at 06:42
  • did you try xdoc.Root ?! – Milad Hosseinpanahi Sep 02 '13 at 06:42
  • 1
    Seeking to avoid the namespace tends to suggest that you're thinking of XML as "just" a formatted string. It's not. And the namespace's are there to *help* you so that you don't accidentally pick up some other element that happens to use the name `SubscriptionOperations` but turns out to have been created for some completely different purpose that your code will never understand (and may completely misinterpret by believing it's about azure) – Damien_The_Unbeliever Sep 02 '13 at 06:45
  • @user2675751 if you mean xdoc.DocumentElement then yes. Same output. – andrewb Sep 02 '13 at 06:45

3 Answers3

1

With the help of Linq

var subscriptionOperations = xdoc.Descendants()
                            .Where(d=>d.Name.LocalName =="SubscriptionOperation");
I4V
  • 34,891
  • 6
  • 67
  • 79
1

My hesitation is in case the namespaces change in the future.

If the namespace changes, then that means that the "contract" has changed. You can't assume that your code can understand such XML unless you also understand the new namespace.

I would say use the namespace in your code, and make sure that your code has a clear failure path for if SelectNodes returns no result.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • I ended up going down this route - adding the namespace to a manager and using that in my Select... calls. Thanks – andrewb Sep 03 '13 at 00:58
0
XmlDocument xdoc = new XmlDocument();
xdoc.Load("file path");
XElement xElement = XElement.Parse(xdoc.OuterXml);
XNamespace xNamespace = xElement.GetDefaultNamespace();
xdoc.LoadXml(xElement.ToString().Replace("xmlns=\"" + xNamespace.ToString() + "\"", ""));     
int nodeCount = xdoc.SelectNodes("/SubscriptionOperationCollection/SubscriptionOperations").Count;

After removing namespace, I am now getting "nodeCount" as 1

Shreya
  • 204
  • 2
  • 7