3

I'm trying to parse a tiny xml return from a web service using LINQ to XML. The XML looks like so:

<ns:ResponseTest xmlns:ns="http://websvc.tst.com">
    <ns:return>true</ns:return>
</ns:ResponseTest>

And looking around online I found this that should read in the first value with the specified name:

var returnValue = XDocument.Parse(xml).Descendants().FirstOrDefault(n => n.Name == "return");

But it's always coming up as null. I also tried using the namespace in the name (when I hover over the name (above: "return") it tells me I can use {namespace}name to provide a namespace) so it was "{ns}return". However that also didn't return anything.

How can I retrieve the return value from the above xml?

EDIT: I also tried the solution here Reading data from XML and the same thing happened. I couldn't get it to find the specified elements.

Community
  • 1
  • 1
Eric B
  • 217
  • 1
  • 14

2 Answers2

5

Try with this:

XNamespace ns = "http://websvc.tst.com";
var returnValue = XDocument.Parse(xml).Descendants(ns + "return").FirstOrDefault();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
3

You can use LocalName to retrieve the unqualified part of the name

var returnValue = XDocument.Parse(xml).Descendants()
                           .FirstOrDefault(n => n.Name.LocalName == "return");
Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27