我正在从网站上拉一根绳子。(我知道我正确地拉它,因为我可以打印整个字符串)。源 XML 字符串:
<feed
xmlns = 'http://www.w3.org/2005/Atom'
xmlns:cap = 'urn:oasis:names:tc:emergency:cap:1.1'
xmlns:ha = 'http://www.alerting.net/namespace/index_1.0'
>
<!-- http-date = Mon, 10 Oct 2013 17:29:01 GMT -->
<id>http://alerts.weather.gov/cap/la.atom</id>
<logo>http://alerts.weather.gov/images/xml_logo.gif</logo>
<generator>NWS CAP Server</generator>
<updated>2013-10-21T17:29:01+00:00</updated>
<author>
<name>w-nws.webmaster@noaa.gov</name>
</author>
<title>Current Watches, Warnings and Advisories for Louisiana Issued by the National Weather Service</title>
<link href='http://alerts.weather.gov/cap/la.atom'/>
<entry>
<id>http://alerts.weather.gov/cap/la.atom</id>
<updated>2013-10-21T17:29:01+00:00</updated>
<author>
<name>w-nws.webmaster@noaa.gov</name>
</author>
<title>There are no active watches, warnings or advisories</title>
<link href='http://alerts.weather.gov/cap/la.atom'/>
<summary>There are no active watches, warnings or advisories</summary>
</entry>
</feed>
我要做的是在每个 [entry] 中提取 [title] 元素的文本(为简单起见,此示例中只有一个,但稍后会有更多)。我不想从 [id] 块中提取 [title]。我如何编写 inside [feed] 的逻辑,找到每个 [entry],在 [entry] 中找到 [title]?一旦我明白了,我就可以把这个值作为一个字符串拉出来就好了。
现在,我有:
XElement root = XElement.Parse(xmlString);
XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom");
String title = (String)
(from elem in root.Descendants(ns + "title") select elem).First();
// for testing purposes: Output element Value
Console.WriteLine(title);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
这是在[feed]下的[id]下写第一个[title]。
非常感谢,TK
编辑使新版本清晰易读:(感谢罗南)
XElement root = XElement.Parse(xmlString);
XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom");
IEnumerable<XElement> xlist =
root.Descendants("entry").Select(elem => elem.Descendants("title").Single());
foreach (XElement el in xlist)
Console.WriteLine("Title: " + el.Value);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
所以这就是它现在的样子。