获取XML的XElement

giz*_*gok 4 c# xml linq xelement

这是我的XML文件:

<Applications>
   <Application Name="Abc">
     <Section Name="xyz">
        <Template Name="hello">
         ...
         ....
         </Template>
      </Section>
   </Application>
   <Application Name="Abc1">
     <Section Name="xyz1">
        <Template Name="hello">
         ...
         ....
         </Template>
      </Section>
   </Application>
Run Code Online (Sandbox Code Playgroud)

我需要做的是根据Template标签的Name属性从给定结构中获取Template XElement.问题是可以有多个具有相同属性Name的模板标签.区别因素是Application Name属性值和section属性值.

目前我能够通过首先根据它的属性获取应用程序元素来获取XElement,然后根据它的属性获取Section,然后根据它的名称获得最终模板.

我想知道是否有办法一次性完成它.

Jon*_*eet 6

我会使用你可以调用Elements或现有序列的事实,所以:

var template = doc.Descendants("Application")
                  .Where(x => (string) x.Attribute("Name") == applicationName)
                  .Elements("Section")
                  .Where(x => (string) x.Attribute("Name") == sectionName)
                  .Elements("Template")
                  .Where(x => (string) x.Attribute("Name") == templateName)
                  .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

您甚至可能想在某处添加扩展方法:

public static IEnumerable<XElement> WithName(this IEnumerable<XElement> elements,
                                             string name)
{
    this elements.Where(x => (string) x.Attribute("Name") == name);
}
Run Code Online (Sandbox Code Playgroud)

然后您可以将查询重写为:

var template = doc.Descendants("Application").WithName(applicationName)
                  .Elements("Section").WithName(sectionName)
                  .Elements("Template").WithName(templateName)
                  .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

...我认为你会同意的是相当可读:)

请注意,使用强制XAttribute转换string代替使用Value属性意味着没有Name属性的任何元素只是被有效地忽略而不是导致a NullReferenceException.