开发者

Is there Better way to read XML Descendants in LINQ-to-XML?

I have code like this:

string result = xml.Root.Descendants("XYZ").Descendants("ABC").Descendants("MNO").Single().Value;

1) Is there a better way to read the value? Some way generic that is not dependent on the nuber of nodes deep that I have to go?

2) What would be the approach to r开发者_StackOverflowemove the hard-coded dependency on "XYZ", "ABC" etc. ?


It's unclear what you really mean, but is this what you're after?

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));
}

Then you can call:

string result = xml.Root.PathDescendants("XYZ", "ABC", "MNO").Single().Value;


If you don't care about the parent node dependency, you can just go straight to "MNO" in your descendants call.

xml.Root.Descendants("MNO")

However, that would produce a sequence of MNO descendants from wherever they might show up in your XML structure.

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

All MNO elements would be in the sequence.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜