LINQ to XML - 仅在某些Parent / Ancestor元素中查找元素

时间:2013-10-21 19:32:53

标签: c# xml linq linq-to-xml

我正在从网站上拉一个字符串。 (我知道我正确地拉它,因为我可以打印整个字符串)。源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>

我要做的是为每个[条目]中的[title]元素拉取文本(为简单起见,此示例中只有一个,但稍后会有更多)。我不想从[id]块中提取[title]。如何编码[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

编辑以使新版本清晰易读:(感谢Ronan)

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();

这就是现在的样子。

1 个答案:

答案 0 :(得分:2)

你正在考虑向下然后向上(标题然后检查父母)而不是向下(获取条目,然后嵌套另一个选择以找到那些标题)

Root.Descendants(ns + "entry")
    .Select(elem=>elem.Descendants(ns + "title").Single());