我应该使用哪个逻辑来获取要从xml文件列出的值

时间:2014-02-03 11:00:39

标签: c# xml xml-parsing

我有一个xml文件,其中包含如下所示的数据:

<NAMES>
    <NAME name="a" Required="true" IsValidationRequired="true">
    <TASKS>
        <TASK name="add"/>
    </TASKS>
    </NAME>
    <NAME name="b" Required="false"  IsValidationRequired="true">
    <TASKS>
        <TASK name="102"/>
    </TASKS>
    </NAME >
</NAMES>

我需要将xml的输出转换为list,它在一条记录中具有以下值

{
Name (attribute in NAME tag), 
Rquired (attribute in NAME tag),
isvalidationreq (attribute in NAME tag),
task (attribute in TASK tag)
}

所以List会有像

这样的结果
  

一,真实,真实的,添加

     

B,FALSE,TRUE,102

由于

1 个答案:

答案 0 :(得分:0)

var xdoc = XDocument.Load(path_to_xml);
var names = from n in xdoc.Root.Elements("NAME")
            select new
            {
                Name = (string)n.Attribute("name"),
                IsRequired = (bool)n.Attribute("Required"),
                IsValidationRequired = (bool)n.Attribute("IsValidationRequired"),
                Tasks = n.Element("TASKS")
                         .Elements("TASK")
                         .Select(t => (string)t.Attribute("name"))
                         .ToList()
            };

结果:

[
  {
     Name: "a",
     IsRequired: true,
     IsValidationRequired: true,
     Tasks: []  // zero items, because there is element Task instead of TASK
  },
  {
    Name: "b",
    IsRequired: false,
    IsValidationRequired: true,
    Tasks: [ "102" ]
  }
]