使用LINQ转换XML并使用C#存储到datagridview表

时间:2016-11-11 06:52:33

标签: c# xml linq datagridview

我有这个XML文件。

<Address>
    <Data2>
        <Person>
          <EMPL_NUM>>100</EMPL_NUM>
          <NAME>Carl</NAME>
          <ID_NUM>1</ID_NUM>
          <IsRequired>0</IsRequired>
        </Person>
        <Person>
          <EMPL_NUM>200</EMPL_NUM>
          <NAME>Mark</NAME>
          <ID_NUM>2</ID_NUM>
          <IsRequired>0</IsRequired>
        </Person>
        <Person>
          <EMPL_NUM>300</EMPL_NUM>
          <NAME>Tanner</NAME>
          <ID_NUM>3</ID_NUM>
          <IsRequired>0</IsRequired>
        </Person>
 </Data2>
</Address>   

我正在尝试将datagridview Person的所有数据存储到ID_NUM = 1

输出到datagrid应为:

EMPL_NUM  |  Name  |  ID_NUM  |  IsRequired                  
  100     |  Carl  |    1     |      0

以下是我目前的代码:

XDocument doc = XDocument.Parse(path);     
var mySteps = (from s in doc.Descendants("Address")                           
               select new
               {
                   Id = int.Parse(s.Element("EMPL_NUM").Value),
                   Name = s.Element("NAME").Value,
                   MD_ID = s.Elements("ID_NUM").Where(x => x.Element("MD_ID").Value == IdNum),
                   Description = s.Element("IsRequired").Value
               }).ToList();
datagridview.datasource = mysteps.ToList();

我一直在收到错误:

Data at the root level is invalid. Line 1, position 1.

我错过了什么?

1 个答案:

答案 0 :(得分:0)

尝试使用

XDocument doc = XDocument.Load(path);

而不是

XDocument doc = XDocument.Parse(path);