我從網站中拉取字符串。 (我知道我拉正確,因爲我可以打印整個字符串)。來源XML字符串:LINQ to 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>[email protected]</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>[email protected]</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>
我試圖做的是拉文爲[標題]元素中的每個[進入]內(there'e唯一一個在本例中爲簡單起見,但會有更多後來)。我不想從[id]塊拉[標題]。如何編碼內部[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();
這是[原料]以書面[ID]上的[標題]。
非常感謝, 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();
所以,這就是它看起來像現在。
所以沒羅南解決您的問題或引導你走向正確的方向?如果是這樣,則將其答案標記爲答案。 –