C # Linq to Sql XML Get closest element in parent

I have some elusive XML that I am trying to read values ​​from.

<text>
  <term>a</term>
  <line>
    <elm>data here</elm>
  </line>
  <term>b</term>
  <line>
    <elm>data here</elm>
  </line>
  <term>c</term>
  <line>
    <elm>data here</elm>
  </line>
</text>

      

I have access to 3 items line

at this point.

As I loop over each line, for the first line, I want to find the element term

that has "a" as the value, since it is "closer" to the first edge.

Same for the second line, except that I want to find the closest element term

, which in this case is "b"

How can I accomplish this using LINQ?

+3


source to share


1 answer


If the element is term

always exactly preceding the element line

, you can use

XElement.ElementsBeforeSelf().Last()

      



So,

var element = XElement.Load(@"previous-sibling.xml");
var termsQuery =
            from line in element.Descendants("line")
            select new
            {
                Elm = line.Descendants("elm").FirstOrDefault().Value,
                Term = line.ElementsBeforeSelf().LastOrDefault().Value
            };

      

+1


source







All Articles