【发布时间】:2016-03-23 05:12:13
【问题描述】:
我正在阅读一些 XML 并将其显示在一个效果很好的 DataGridView 中。
但是,如果我能抓取特定元素并阅读它们的内容,我的生活会轻松 10 倍。 (我使用 XmlReader)
另外,有没有一种简单的方法来循环一个元素?我需要获取计数,然后遍历每个“设施”,但我似乎无法让它正常工作。添加另一个“While(read)”并不是一个很好的解决方案。
我现在不想切换到另一个阅读器,我现在对这个很深入。
XML 数据:
<data>
<count>2</count>
<facility>
<typeId>1</typeId>
<type>Beds</type>
<quantity>0</quantity>
<description>null</description>
</facility>
<facility>
<typeId>2</typeId>
<type>EDBeds</type>
<quantity>0</quantity>
<description>null</description>
</facility>
</data>
代码:
while (xr.Read())
{
if (xr.Name.Equals("count"))
{
valueName.Text = "We currently have " + xr.ReadElementContentAsString() + " facilities open.";
}
while (xr.ReadToFollowing("facility"))
{
//Add a new row for data if we are at a new Facility element
if (xr.NodeType == XmlNodeType.Element && xr.Name == "facility")
{
row = generalData.Rows.Add();
col = 0;
}
//Loop through current facility Element
}
}
【问题讨论】: