2011-03-16 77 views
1

我無法匿名抓取元素。我不想按名稱調用這些元素。第二個foreach語句只是將整個部分視爲單個元素。如何循環遍歷所有的值,而不用通過名字來調用每個值?我打算做linq語句,但從我讀過的每個示例中,我都沒有看到如何在不按名稱調用每個元素的情況下使用這些語句。謝謝你的幫助!C#XDocument,幫助匿名抓取元素

public class box 
{ 
    public List<Person> People { get; set; } 
} 

public class Person 
{ 
    public Dictionary<string, string> data { get; set; } 
} 

/* 

<outer> 
    <xml> 
     <person> 
      <data> 
      <house>Big</house> 
      <cell>911</cell> 
      <address>NA</address> 
      </data> 
     </person> 
     <person> 
      <data> 
      <house>Big</house> 
      <cell>911</cell> 
      <address>NA</address> 
      </data> 
     </person> 
     <person> 
      <data> 
      <house>Big</house> 
      <cell>911</cell> 
      <address>NA</address> 
      </data> 
     </person> 
     <person> 
      <data> 
      <house>Big</house> 
      <cell>911</cell> 
      <address>NA</address> 
      </data> 
     </person> 
    </xml> 
</outer> 

*/ 


this.box.People = new List<Person>(); 

foreach (var ele in xml.Descendants("person")) 
{ 
    Person somebody = new Person 
    { 
     data = new Dictionary<string, string>(), 
    }; 

    foreach (var temp in ele.Descendants("data")) 
    { 
     somebody.data.Add(temp.Name.ToString(), temp.Value.ToString()); 
    } 

    this.box.People.Add(somebody); 
} 

回答

1

此作品(測試) - 只是缺少Elements()部分:

foreach (var temp in ele.Descendants("data").Elements()) 
{ 
    somebody.data.Add(temp.Name.ToString(), temp.Value); 
} 
+0

我不認爲這會連編譯:-) – 2011-03-16 19:35:40

+0

爲什麼你會這麼認爲嗎?我測試了這個,名稱和值被正確提取 – BrokenGlass 2011-03-16 19:38:31

+0

「元素()」需要一個參數才能工作。 – PiZzL3 2011-03-16 19:56:29

0
foreach (var temp in ele.Descendants("data")) 
{ 
    foreach(var valueElem in temp.Elements()) 
    { 
     somebody.data.Add(valueElem.Name.LocalName, valueElem.Value); 
    } 
} 
1

此代碼走的元素和XML文檔中的屬性。您不必爲Elements()方法提供名稱。

XDocument xmlDoc = new XDocument(); 
foreach (XElement element in xmlDoc.Elements()) { 
    // .. Do something with the element 
    foreach (XAttribute attribute in element.Attributes()) { 
     // .. Do something with the attribute 
    } 
}