简体   繁体   中英

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());
        }
    }
}

Apple

Apple
Manglo

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

I want to achieve this with XmlReader 我想用XmlReader实现这一点

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();
}

In case anybody wants to know how to get the OuterXml for each child nodes as well use the child node value, following code can be used:

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

using (XmlReader xmlReader = XmlReader.Create(new StringReader(str)))
{
    while (!xmlReader.EOF)
    {
        if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "B")
        {
            XElement xElement = XNode.ReadFrom(xmlReader) as XElement;
            Console.WriteLine(xElement.ToString());     // This will print the tag
            Console.WriteLine(xElement.Value);          // This will print the tag value
        }
        else
        {
            xmlReader.Read();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM