简体   繁体   English

C#Linq XML从文档中提取节点

[英]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! 我正在尝试使用Linq XML选择多个节点和子节点,但感到困惑!

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. 在下面的示例XML中,我需要提取所有<MostWanted>和所有Wanted及其子节点,但在Mostwanted和Wanted节点之间不包含其他节点。

This because each MostWanted can be followed by any number of Wanted and the Wanted relate to the preceding Mostwanted. 这是因为每个MostWanted都可以跟随任意数量的通缉,并且通缉犯与之前的通缉犯有关。

I'm even confusing myself typing this up!!! 我什至让我自己打扰了!!!

How can I do this in C#?? 如何在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". 这将检索称为“ Wanted”或“ 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. 如果这不是您要解决的问题,请澄清您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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