2015-06-10 145 views
0

我有一個XML文檔,我試圖從中提取數據。使用特定索引遍歷元素列表中的元素列表

<folder> 
<list index="1"> 
<item index="1" > 
<field type="IMAGE"> 
<url>https://www.test.com/0001.png</url> 
</field> 
</item> 
<item index="2"> 
<field type="IMAGE"> 
<url>https://www.test.com/0002.png</url> 
</field> 
</item> 
</list> 

等等

我試圖讓有型「形象」與索引列表內的所有字段的列表1.在XML多個列表但他們有其他索引,但我只想從索引1列表中提取。我該怎麼辦?

我試圖做的:

foreach (var list in xmlDoc.Descendants("list")) 
{ 
    if (list.Attribute("index").Value == "1") // GET THE LIST 
    { 
     foreach (var field in list) 
     { 
      if (field.Attribute("type") != null && field.Attribute("type").Value == "IMAGE") 
      { 
       MessageBox.Show(field.Element("url").Value); 
      } 
     } 
    } 
} 

但是這是給我的錯誤信息:

錯誤2 foreach語句不能 型「的變量操作System.Xml.Linq.XElement '因爲'System.Xml.Linq.XElement'不包含 包含'GetEnumerator'的公共定義

我該如何解決這個問題?

回答

3

你試圖直接迭代的元素,你需要遍歷其子域元素,所以不是:

foreach (var field in list) 

你想:

foreach (var field in list.Descendants("field")) 

這就是說,一個更容易的方法是利用LINQ:

var urls = xmlDoc.Descendants("list") 
    .Where(e => (int)e.Attribute("index") == 1) 
    .Descendants("field") 
    .Where(e => (string)e.Attribute("type") == "IMAGE") 
    .Select(e => (string)e.Element("url")); 
+0

非常感謝! – Cainnech

1

因爲問題有xpath tag :)

//list[@index="1"]//field[@type="IMAGE"]/url/text() 
+0

對此我很抱歉,但是我擔心我並不真正瞭解Linq和XPath之間的區別,所以我將它們放在那裏:-)但是,謝謝您的建議! – Cainnech