我正在尝试使用XDocument
中的Xelement
和C#
来获取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)
这对我有用,请看一下。
W/System.err: java.lang.RuntimeException: Stub!
at com.google.android.things.pio.PeripheralManager.getInstance(PeripheralManager.java:21)
at com.eurotronik.library.common.serial.SerialClass.<init>(SerialClass.java:38)
at com.eurotronik.nursetabmode.serialport.SerialPortService.onCreate(SerialPortService.java:112)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3192)
at android.app.ActivityThread.-wrap5(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1568)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)