Adrian
Adrian

Reputation: 13

C# Linq XML pull out nodes from document

I’m trying to use Linq XML to select a number of nodes and the children but getting terrible confused!

In the example XML below I need to pull out all the <MostWanted> and all the Wanted with their child nodes but without the other nodes in between the Mostwanted and Wanted nodes.

This because each MostWanted can be followed by any number of Wanted and the Wanted relate to the preceding Mostwanted.

I’m even confusing myself typing this up!!!

How can I do this in C#??

<root>
  <top>
    <NotWanted3>
    </NotWanted3>
    <MostWanted>
      <UniqueKey>1</UniqueKey>
      <QuoteNum>1</QuoteNum>
    </MostWanted>
    <NotWanted2>
      <UniqueKey>1</UniqueKey>
      <QuoteNum>1</QuoteNum>
    </NotWanted2>
    <NotWanted1>
      <UniqueKey>0001</UniqueKey>
    </NotWanted1>
    <Wanted>
      <Seg>
        <SegNum>1</SegNum>
      </Seg>
    </Wanted>
    <Wanted>
      <Seg>
        <SegNum>2</SegNum>
      </Seg>
    </Wanted>
    <NotWanted>
      <V>x</V>
    </NotWanted>
    <NotWanted3>
    </NotWanted3>
    <MostWanted>
      <UniqueKey>1</UniqueKey>
      <QuoteNum>1</QuoteNum>
    </MostWanted>
    <NotWanted2>
      <UniqueKey>1</UniqueKey>
      <QuoteNum>1</QuoteNum>
    </NotWanted2>
    <NotWanted1>
      <UniqueKey>0002</UniqueKey>
    </NotWanted1>
    <Wanted>
      <Seg>
        <SegNum>3</SegNum>
      </Seg>
    </Wanted>
    <Wanted>
      <Seg>
        <SegNum>4</SegNum>
      </Seg>
    </Wanted>
    <NotWanted>
      <V>x</V>
    </NotWanted>
  </top>
</root>

Upvotes: 1

Views: 352

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500565

Why don't you just use:

XName wanted = "Wanted";
XName mostWanted = "MostWanted";
var nodes = doc.Descendants()
               .Where(x => x.Name == wanted || x.Name == mostWanted);

That will retrieve every element called "Wanted" or "MostWanted". From each of those elements you can get to the child elements etc.

If this isn't what you're after, please clarify your question.

Upvotes: 1

Related Questions