简体   繁体   English

如何使用 XmlReader 检测没有子 xml 节点?

[英]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?使用 XmlReader? The problem is that I am not been able to know whether a node contains child or not using XmlReader .问题是我无法使用XmlReader知道节点是否包含子节点。

See MSDN: XmlReader.Read Method - "When overridden in a derived class, reads the next node from the stream."请参阅 MSDN: XmlReader.Read 方法- “当在派生的 class 中被覆盖时,从 stream 读取下一个节点。”

There is an example on that MSDN page, however I think you want to do something like this:该 MSDN 页面上有一个示例,但是我认为您想做这样的事情:

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();诀窍是当您了解每次 go 围绕while循环并调用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.您前进到下一个节点,因此当您调用reader上的任何其他方法/属性时,它们将作用于当前节点的任何内容。

As an alternative you could use XPath and check the XmlNode.HasChildNodes property.作为替代方案,您可以使用 XPath 并检查XmlNode.HasChildNodes属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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