我无法匿名抓取元素。我不想按名称调用元素。第二个foreach语句只是抓住整个部分,好像它是一个单独的元素。如何在不通过名称调用每个值的情况下循环显示所有值?我愿意做linq语句,但是从我读过的每个例子中,我都看不到如何在不调用每个元素的情况下使用它们。谢谢你的帮助!
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);
}
答案 0 :(得分:1)
这有效(测试) - 只是错过了Elements()
部分:
foreach (var temp in ele.Descendants("data").Elements())
{
somebody.data.Add(temp.Name.ToString(), temp.Value);
}
答案 1 :(得分: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
}
}
答案 2 :(得分:0)
foreach (var temp in ele.Descendants("data"))
{
foreach( var valueElem in temp.Elements() )
{
somebody.data.Add(valueElem.Name.LocalName, valueElem.Value);
}
}
答案 3 :(得分:0)