Search code examples
c#xmlxmlreader

XmlReader: Not reading sibling child elements


Following is the code:

string str = "<A><B>Apple</B><B>Mango</B></A>";

using (XmlReader xmlReader = XmlReader.Create(new StringReader(str)))
{
    while (xmlReader.Read())
    {
        if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "B")
        {
            Console.WriteLine(xmlReader.ReadElementContentAsString());
        }
    }
}

Output:

Apple

Supposed Output:

Apple
Manglo

Can you please help me to understand what is wrong with this code? How do I get the supposed output?

Note: I want to achieve this with XmlReader


Solution

  • ReadElementContentAsString reads and advances the reader to the next element.
    So with the Read in the while you are skipping the next B element.

    Instead use, the Value property.

    using (XmlReader xmlReader = XmlReader.Create(new StringReader(str)))
    {
        while (xmlReader.Read())
        {
            if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "B")
            {
                xmlReader.Read(); // Next read will contain the value
                Console.WriteLine(xmlReader.Value);
            }
        }
    }
    

    If you wish to show the outer xml then use it a bit differently:

    bool hasMore = xmlReader.Read();
    while (hasMore)
    {
        if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "B")
        {
            Console.WriteLine(xmlReader.ReadOuterXml());
        }
        else hasMore = xmlReader.Read();
    }