I couldn't do a lot while trying to read XML. I'm a beginner in C#, I want to parse the following XML using a XmlTextReader as an example.
I take p1 and p2, but I couldn't reach p24 and p26. How should I proceed?
This is my XML:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Books>
<pb>
<p1>1</p1>
<p2>2</p2>
<p24>
<a>
<a1>97924</a1>
<a2>Fabio Moon</a2>
</a>
<a>
<a1>82056</a1>
<a2>Gabriel Ba</a2>
</a>
</p24>
<p26>
<ca>
<ca1>001005</ca1>
<ca2>Çocuk Kitapları</ca2>
<ca3>
<ca1>001005016</ca1>
<ca2>Roman</ca2>
</ca3>
<ca3>
<ca1>001005017</ca1>
<ca2>Öykü</ca2>
</ca3>
</ca>
</p26>
</pb>
</Books>
</Products>
C#:
while (xmlTextReader.Read())
{
if (xmlTextReader.NodeType == XmlNodeType.Element && xmlTextReader.Name == "p1")
{
Console.WriteLine(xmlTextReader.Value);
}
}
The problem is the code is only looking for the
p1element (xmlTextReader.Name == "p1"in the if condition).I modified the code from XmlTextReader Examples to suit your needs. If you want to get the text values too you need to check whether the node is type
XmlNodeType.Text. Then you can usexmlTextReader.Nameto get the tag name and usexmlTextReader.Textto get the inner text.If you only want to read children of the
<pb>element then you can useReadToDescendant.The code below should read your whole xml and print it to the console: