0

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); 
    }
}
haldo
  • 14,512
  • 5
  • 46
  • 52
matematikistan
  • 127
  • 1
  • 6

1 Answers1

1

The problem is the code is only looking for the p1 element (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 use xmlTextReader.Name to get the tag name and use xmlTextReader.Text to get the inner text.

If you only want to read children of the <pb> element then you can use ReadToDescendant.

The code below should read your whole xml and print it to the console:

// read to 'pb' element and then read it's children
xmlTextReader.ReadToDescendant("pb");
while (xmlTextReader.Read())
{
    switch (xmlTextReader.NodeType)
    {
        case XmlNodeType.XmlDeclaration:
            Console.WriteLine("<?xml version='1.0' encoding='uft-8'?>");
            break;
        case XmlNodeType.Element:
            Console.WriteLine("<{0}>", xmlTextReader.Name);
            break;
        case XmlNodeType.Text:
            Console.WriteLine(xmlTextReader.Value);
            break;            
        case XmlNodeType.EndElement:
            Console.WriteLine("</{0}>", xmlTextReader.Name);
            break;
    }
}
// remember to close the reader
if (xmlTextReader != null)
    xmlTextReader.Close();
haldo
  • 14,512
  • 5
  • 46
  • 52