tags:

views:

158

answers:

1

So i have this simple XML text:

<errors xmlns="http://schemas.google.com/g/2005"&gt;
  <error>
    <domain>GData</domain>
    <code>InvalidRequestUriException</code>
    <internalReason>You must specify at least one metric</internalReason>
  </error>
</errors>

What the simplest way to extract the value of the internalReason element?

+6  A: 

You need to specify the namespace when finding descendants. For example:

var xml = XElement.Load("test.xml");
XNamespace ns = "http://schemas.google.com/g/2005";
var reason = xml.Descendants(ns + "internalReason").First().Value;

Or:

 var xml = XElement.Load("test.xml");
 XNamespace ns = "http://schemas.google.com/g/2005";
 var reason = xml.Elements(ns + "error").First()
                 .Elements(ns + "internalReason").First().Value;

(I'm not keen on using query expressions when they don't really provide any extra value.)

You might also want to split it up and use FirstOrDefault so that you can check whether the elements you're asking for are present or not.

Jon Skeet
Yup, it was the namespace. Thanks.
Jason Miesionczek