.net - Read particular depth XML ELEMENTS using XmlReader in C# -


i have xml file nodes @ different depths. need code read specific depth nodes not all, , using xmlreader in c#.

can me in this?

below xml structure. want read "depth2" nodes.

<depth0>     <depth1>         <depth2/>         <depth2/>         <depth2/>     </depth1>     <depth1>         <depth2/>         <depth2/>         <depth2/>     </depth1>     <depth1>         <depth2/>         <depth2/>         <depth2/>     </depth1> </depth0> 

code:

using (var reader = xmlreader.create("d:\\xyz.xml")) {     while (reader.read())     {         if (reader.depth == 4 && reader.nodetype == xmlnodetype.element)         {             xmlreader chnode = reader.readsubtree();             additems(chnode);         }         else             reader.movetoelement();        } } 

you can use descendants function:

var result = xdocument.load("data.xml").root                       .descendants("depth2"); 

it find depth2 elements anywhere under xml's root


for xmlreader way can:

list<xmlnode> nodes = new list<xmlnode>(); using (var reader = xmlreader.create("data.xml")) {     xmldocument document = new xmldocument();     while (reader.read())     {         if (reader.depth == 2 && reader.nodetype == xmlnodetype.element)         {             xmlnode node = document.createnode(xmlnodetype.element, reader.name, "");             //here added inner xml can whatever need             node.innerxml = reader.readinnerxml();              nodes.add(node);         }         reader.movetoelement();     } } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -