简体   繁体   中英

How to select specific XML node in c#?

XML,

 <A>
    <B  id="ABC">
      <C name="A" />
      <C name="B" />
      <C name="C" />
      <C name="G" />
    </B>
    <B id="ZYZ">
      <C name="1" />
      <C name="2" />
      <C name="3" />
      <C name="4" />
    </B>
  </A>

I Need to select only <C> nodes and assign to a variable.

I'm using following c# code which is not working,

var asdf = c.Elements("C");

asdf should contain ,

<C name="A" />
<C name="B" />
<C name="C" />
<C name="G" />
<C name="1" />
<C name="2" />
<C name="3" />
<C name="4" />

Any help appreciated!

You need Descendants like:

var cNodes = document.Descendants("C");

For output:

foreach (var item in cNodes)
{
    Console.WriteLine(item);
}

You will get:

<C name="A" />
<C name="B" />
<C name="C" />
<C name="G" />
<C name="1" />
<C name="2" />
<C name="3" />
<C name="4" />

this run:

XElement x = XElement.Parse("your_xml_string");

var asdf=x.Elements("B").Elements("C");

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