I have an XML file with some nodes at different depths. I need a code to read only specific depth nodes but not all, and only by using XmlReader in C#.
Can someone help me in this?
Below is my XML structure. I want to read only "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 the Descendants
function:
var result = XDocument.Load("data.xml").Root
.Descendants("Depth2");
It will find for you all the Depth2
elements anywhere under the xml's Root
For an XmlReader
way you 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 I just added all the inner xml but you can do whatever you need
node.InnerXml = reader.ReadInnerXml();
nodes.Add(node);
}
reader.MoveToElement();
}
}