XMLParser跳过一组标签中的最后一个标签

时间:2012-04-27 22:38:36

标签: c# .net xml datatable xml-parsing

我正在将XML文件读入这样的数据表:

DataTable dt = XMLParser.XMLRead.ReadeFormXMLFile(filePath, "my:myFields");

但它没有捕获所有字段。

有多个从业者姓名和从业者第一名和从业者NPI:

 <my:group1>
    <my:group2>
      <my:PractitionerFirstName>Joe</my:PractitionerFirstName>
      <my:PractitionerLastName>Limits</my:PractitionerLastName>
      <my:PractitionerNPI>0987654321</my:PractitionerNPI>
      <my:PractitionerDegree>MD</my:PractitionerDegree>
    </my:group2>
    <my:group2 xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-02-06T05:56:10">
       <my:PractitionerFirstName>Him</my:PractitionerFirstName>
       <my:PractitionerLastName>Haw</my:PractitionerLastName>
       <my:PractitionerNPI>1234567890</my:PractitionerNPI>
       <my:PractitionerDegree>PA</my:PractitionerDegree>
     </my:group2>
     <my:group2 xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-02-06T05:56:10">
        <my:PractitionerFirstName>Mike</my:PractitionerFirstName>
        <my:PractitionerLastName>Kim</my:PractitionerLastName>
        <my:PractitionerNPI>1234567890</my:PractitionerNPI>
        <my:PractitionerDegree>DO</my:PractitionerDegree>
     </my:group2>
     <my:group2 xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-02-06T05:56:10">
       <my:PractitionerFirstName>Vanilla </my:PractitionerFirstName>
       <my:PractitionerLastName>Ice</my:PractitionerLastName>
       <my:PractitionerNPI>1231231231</my:PractitionerNPI>
       <my:PractitionerDegree>MD</my:PractitionerDegree>
     </my:group2>
     <my:group2 xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-02-06T05:56:10">
       <my:PractitionerFirstName>Kim</my:PractitionerFirstName>
       <my:PractitionerLastName>John</my:PractitionerLastName>
       <my:PractitionerNPI>1234567890</my:PractitionerNPI>
       <my:PractitionerDegree>DO</my:PractitionerDegree>
     </my:group2>
  </my:group1>

然而,他们并未被包括在内。它目前正在做的是在group2中取LAST记录并忽略此前的所有记录:

<my:PractitionerFirstName>Kim</my:PractitionerFirstName>
<my:PractitionerLastName>John</my:PractitionerLastName>
<my:PractitionerNPI>1234567890</my:PractitionerNPI>
<my:PractitionerDegree>DO</my:PractitionerDegree>

问题:什么会导致XML解析器只抓取group2中的最后一条记录而忽略其他所有记录?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

XElement root = XElement.Load(filePath);
var list = root.Elements().Select(x => new
    {
        FirstName = x.Get("PractitionerFirstName", string.Empty),
        LastName = x.Get("PractitionerLastName", string.Empty),
        NPI = x.Get("PractitionerNPI", string.Empty),
        Degree = x.Get("PractitionerDegree", string.Empty)
    }).ToArray();

这可以使用您提供的xml。我正在使用Get extension method from here