【发布时间】:2020-02-05 12:07:34
【问题描述】:
我正在尝试使用 C# 中的 XDocument 和 Xelement 获取 xml 数据。我正在使用IEnumerable<XElement> 来遍历我想要获取的所有元素。我的问题是,IEnumerable<XElement> 多次获取相同的数据,当我使用foreach 循环时,它循环的次数超过了我的 xml 文件中的元素数。它在每个循环中获取相同的东西。有什么建议吗?
我的 XML 文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SYSTEM SelectedConfiguration = "5840-0000-0001">
<Configuration Name = "5840-0000-0001">
<Users>
<User>
<Name>Lebron</Name>
<Surname>James</Surname>
<Adress>asdfgh</Adress>
<Phone>1234</Phone>
<Gender>Male</Gender>
<Country>USA</Country>
</User>
<User>
<Name>Kevin</Name>
<Surname>Durand</Surname>
<Adress>asdfghasdfgh</Adress>
<Phone>4567</Phone>
<Gender>Male</Gender>
<Country>USA</Country>
</User>
<User>
<Name>Stephen</Name>
<Surname>Curry</Surname>
<Adress>zxcv</Adress>
<Phone>1267</Phone>
<Gender>Male</Gender>
<Country>USA</Country>
</User>
</Users>
</Configuration>
</SYSTEM>
我的代码:
XDocument devices = XDocument.Load(Application.StartupPath + "\\Users.xml");
XElement conf = devices.Root.Element("Configuration");
/*
IEnumerable<XElement> childElements =
from el in conf.Element("Instruments").Elements("Instrument")
select el;
*/
IEnumerable<XElement> childElements = conf.Element("Users").Elements("User");
int counter = childElements.Count();
foreach (XElement el in childElements)
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = el.Element("Name").Value.ToString();
row.Cells[1].Value = el.Element("Surname").Value.ToString();
row.Cells[2].Value = el.Element("Adress").Value.ToString();
dataGridView1.Rows.Add(row);
// if (counter-- <= 1)
// return;
}
我得到的结果:
如图所示,有不止一个 Lebron James 或 Kevin Durand,foreach正在循环遍历这些节点的每个组合,如图 3 所示。
编辑 1:
程序多次循环回到IEnumerable<XElement> childElements = conf.Element("Users").Elements("User"); 行。计数器一次又一次地变为 3。
【问题讨论】:
-
不,您的图像显示节点 0 具有一个名称,而节点 1 具有另一个名称。如果展开节点,您会看到基类,而不是其他对象。你的计数器真的不是 3 吗?
-
这段代码
dataGridView1.Rows[0].Clone()第一次怎么不会产生IndexOutOfRangeException,Rows[0]是从哪里来的? -
我建议您在开始日常活动时尝试致电
dataGridView1.Rows.Clear();。 -
@Holger 它循环回 IEnumerable
childElements = conf.Element("Users").Elements("User");线几次。我不明白。我的计数器得到 3,但如果我没有在代码末尾添加返回值,它会一次又一次地得到 3。 -
如果您启用添加新行,@RandRandom dataGridView 将在开头带有 1 个空行。
标签: c# .net xml linq-to-xml ienumerable