views:

76

answers:

1

Hi 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>
+1  A: 

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.

Jon Skeet
Thanks Jon this wors great!
Adrian
i'm new to this as I'm sure you can tell!
Adrian
could you explain how it works "=> "?
Adrian
@Adrian: Not right now, as I'm about to walk home. However, search for "lambda expressions" - and basically get a book about C# 3, or read a C# 3 tutorial online. It'll go into a lot more detail :)
Jon Skeet
@Adrian try this books http://www.amazon.com/C-Depth-Jon-Skeet/ :). And mark Jon's answer.
Sergey Mirvoda
@Jon Thanks Jon I will check your book out on amazon.co.uk
Adrian
@Sergey thank you for the link to Jon's book and yes I have marked the question as answered.
Adrian