简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM