简体   繁体   中英

How to detect no child xml node using XmlReader?

How to differenciate between the two nodes

<Header Name="ABC" />
and
<Test Test="AA">
Hello
</Test>

using XmlReader? The problem is that I am not been able to know whether a node contains child or not using XmlReader .

See MSDN: XmlReader.Read Method - "When overridden in a derived class, reads the next node from the stream."

There is an example on that MSDN page, however I think you want to do something like this:

using(var reader = XmlReader.Create(stream))
{
    while(!reader.EOF)
    {
        reader.Read();

        if(reader.IsEmptyElement)
        {
            ...
        }
    }
}

The trick is when you understand that each time you go round the while loop and call reader.Read(); you advance to the next node, so when you call any other methods/properties on the reader , they will act on whatever the current node is.

As an alternative you could use XPath and check the XmlNode.HasChildNodes property.

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