2013-10-21 159 views
1

我從網站中拉取字符串。 (我知道我拉正確,因爲我可以打印整個字符串)。來源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(); 

所以,這就是它看起來像現在。

+1

所以沒羅南解決您的問題或引導你走向正確的方向?如果是這樣,則將其答案標記爲答案。 –

回答

2

你轉到先降後升逆向思維(標題,然後檢查父),而不是僅僅下降(獲取條目,然後窩另一個選擇找到這些標題)

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

謝謝。我花了一分鐘才弄清楚IEnumerable xlist =你的建議。所以它給了我一個元素列表(對嗎?)。當我嘗試下面的打印語句時,它會給出一個空集,不會打印任何內容。 'Foreach(xlist中的XElement el) Console.WriteLine(「Title:」+ el.Value);'建議? – TK421

+0

你必須提供完整的代碼。無法幫助,如果我沒有看到xlist的定義。在我的示例中,您只需簡單地列出標題元素列表,以便您的代碼看起來正確。 –

+0

editted original post所以你可以閱讀新的代碼。在調試器中逐步完成時,它看起來像xlist永遠不會從null更改。 – TK421