简体   繁体   中英

LINQ to XML can't get element

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.

Try with this:

XNamespace ns = "http://websvc.tst.com";
var returnValue = XDocument.Parse(xml).Descendants(ns + "return").FirstOrDefault();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM