C# XDocument,帮助匿名抓取元素
我无法匿名获取元素。我不想直呼元素的名字。第二个 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);
}
I'm having trouble grabbing elements anonymously. I don't want to call the elements by name. The second foreach statement just grabs the entire section as if it's a single element. How do I cycle through all the values in without calling each one by name? I'm open to doing linq statements, but from every example I've read, I don't see how I can use those without calling each element by name. Thanks for any help!
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这有效(已测试) - 只是缺少
Elements()
部分:This works (tested) - was just missing the
Elements()
part:此代码遍历 xml 文档中的元素和属性。您不必为 Elements() 方法提供名称。
This code walks the elements and attributes within an xml document. You don't have to provide a name to the Elements() method.
如果我理解正确,您可能需要查看:
http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx
If i'm understanding correctly, you may want to look into:
http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx