Basic LINQ to XML Question
I have an .asmx webservice th开发者_Python百科at returns some XML. A sample bit of XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">http://www.mydomain.com/sample.txt</string>
I'm new to LINQ but would like to get familiar with it. I need to get the value of inside the string element. But I'm not sure how to do it with LINQ. Currently, I'm trying:
string text = GetXmlText();
XDocument xml = XDocument.Parse(text);
string url = xml.Descendants("string").SingleOrDefault().Value;
This code throws an exception. But I'm not sure what I'm doing wrong. How do I get the response value with LINQ?
Thanks!
For this particular usage, all you need is this, because the XML you provided contains only a root node and you want its value.
string url = xml.Root.Value;
If the XML is indeed more complicated, please elaborate. But take a look at the xmlns
attribute in the string
element. To handle situations when you would like to refer to a particular element or descendant directly, you need to utilize an XNamespace
object.
XNamespace ns = "http://tempuri.org/";
string url = (string)xml.Descendants(ns + "string").FirstOrDefault();
精彩评论