C# 有没有更好的方法来读取LINQ到XML中的XML子体?

C# 有没有更好的方法来读取LINQ到XML中的XML子体?,c#,generics,linq-to-xml,C#,Generics,Linq To Xml,我有这样的代码: string result = xml.Root.Descendants("XYZ").Descendants("ABC").Descendants("MNO").Single().Value; 1) 有没有更好的方法读取值?某种不依赖于我必须去的节点数的通用方法 2) 删除“XYZ”、“ABC”等硬编码依赖项的方法是什么?如果不关心父节点依赖项,可以直接在子代调用中转到“MNO” xml.Root.substands(“MNO”) 但是,这将从XML结构中可能出现的任何位置

我有这样的代码:

string result = xml.Root.Descendants("XYZ").Descendants("ABC").Descendants("MNO").Single().Value;
1) 有没有更好的方法读取值?某种不依赖于我必须去的节点数的通用方法


2) 删除“XYZ”、“ABC”等硬编码依赖项的方法是什么?

如果不关心父节点依赖项,可以直接在子代调用中转到
“MNO”

xml.Root.substands(“MNO”)

但是,这将从XML结构中可能出现的任何位置生成一系列
MNO
子体

<root>
   <MNO />
   <ABC>
      <MNO />
   </ABC>
   <ABC>
      <XYZ>
         <MNO />
      </XYZ>
   </ABC>
</root>


所有
MNO
元素都将在序列中。

如果您不关心父节点依赖性,您可以直接在子代调用中转到
“MNO”

xml.Root.substands(“MNO”)

但是,这将从XML结构中可能出现的任何位置生成一系列
MNO
子体

<root>
   <MNO />
   <ABC>
      <MNO />
   </ABC>
   <ABC>
      <XYZ>
         <MNO />
      </XYZ>
   </ABC>
</root>


所有的
MNO
元素都会在序列中。

不清楚你真正的意思,但这就是你想要的吗

public IEnumerable<XElement> PathDescendants(
    this XElement element,
    params XName[] names)
{
    return new[] { element }.PathDescendants(names);
}

public IEnumerable<XElement> PathDescendants(
    this IEnumerable<XElement> elements,
    params XName[] names)
{
    return names.Aggregate(elements,
                           (current, name) => current.Descendants(name));
}

不清楚你的真正意思,但这就是你想要的吗

public IEnumerable<XElement> PathDescendants(
    this XElement element,
    params XName[] names)
{
    return new[] { element }.PathDescendants(names);
}

public IEnumerable<XElement> PathDescendants(
    this IEnumerable<XElement> elements,
    params XName[] names)
{
    return names.Aggregate(elements,
                           (current, name) => current.Descendants(name));
}

是否可以包含一段您正在查询的XML文档以帮助我们理解您的查询?是否可以包含一段您正在查询的XML文档以帮助我们理解您的查询?是;但是在实现这一点时,我得到一个错误,即扩展方法应该是静态的。这些是作为扩展方法使用的吗?@GilliVilla:对不起,是的-它们应该是静态的,并且在非通用的顶级静态类中。是的;但是在实现这一点时,我得到一个错误,即扩展方法应该是静态的。这些是作为扩展方法使用的吗?@GilliVilla:对不起,是的-它们应该是静态的,并且在非通用的顶级静态类中。