开发者

How to detect no child xml node using XmlReader?

开发者 https://www.devze.com 2023-03-28 14:53 出处:网络
How to differenciate between the two nodes <Header Name=\"ABC\" /> and <Test Test=\"AA\"> Hello

How to differenciate between the two nodes

<Header Name="ABC" />
and
<Test Test="AA">
Hello
<开发者_JAVA百科/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.

0

精彩评论

暂无评论...
验证码 换一张
取 消