检查 XML 元素是否有子元素或值 [英] Check whether an XML Element has child elements or a value

查看:39
本文介绍了检查 XML 元素是否有子元素或值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 .NET 的 XMLDocument 作为 XML 文件的容器,当我使用时:

Im using .NET's XMLDocument as a container for an XML file and when I use:

document.GetElementsByTagName("ElementX")[0].HasChildNodes

即使元素看起来像这样,它也会对所有元素返回 true:

It returns true for all elements even when the element looks like so:

<ElementX>
    <A>1</A>
    <B>2</B>
    Some value
</ElementX>

<ElementX>Some Value</ElementX>

示例一个显然有子元素,但第二个示例似乎还没有都返回 true.我猜 XMLDocument 将任何值(即使它不是元素)计为子值?有没有办法可以检查元素是否只包含文本或元素.提前致谢.

Example one clearly has child elements but the second example does not yet both seem to return true. Im guessing that XMLDocument counts any value (Even if its not an element) as a child? Is there a way I can check if an element contains just text or an element(s). Thanks in advance.

推荐答案

您当前的代码:

document.GetElementsByTagName("ElementX")[0].HasChildNodes

正在返回该根节点 ElementX.GetElementsByTagName 返回与该标记名匹配的元素的 XmlNodeList.所以你只是得到根,它有子节点.

is returning that root node ElementX. GetElementsByTagName returns an XmlNodeList of elements matching that tagname. So you're just getting the root, which has child nodes.

但是,如果我的问题是正确的,那并不能解决您的问题,因为根据此库,这些文本值 1 和 2 是节点!喘气!不过,它们是 XmlText 对象,而不是元素.

But that won't solve your problem, if I have your question right, because those text values 1 and 2 are nodes according to this library! Gasp! They're XmlText objects though, not elements.

您是否正在寻找其下方具有 XmlElement 的任何节点?如果是这样,您可能正在寻找这个:

Are you looking for any node that has an XmlElement underneath it? If so, you are probably looking for this:

child.ChildNodes.OfType<XmlElement>().Any()

运行这个 humdinger 看看我的意思:

Run this humdinger to see what I mean:

internal static class Program
{
    private static void Main()
    {
        var doc = new XmlDocument();
        doc.LoadXml("<ElementX><A>1</A><B>2</B>Some value</ElementX>");
        Console.WriteLine("{0,15}{1,15}{2,15}{3,15}","Name","Children","ChildElements","Value");
        foreach (XmlElement e in doc.GetElementsByTagName("ElementX"))
            ChildNodeCheck(e);
    }

    private static void ChildNodeCheck(XmlNode element)
    {
        Console.WriteLine("{0,15}{1,15}{2,15}{3,15}", 
            element.Name, 
            element.HasChildNodes, 
            element.ChildNodes.OfType<XmlElement>().Any(), 
            element.Value);

        if (!element.HasChildNodes) return;
        foreach(XmlNode child in element.ChildNodes)
            ChildNodeCheck(child);
    }
}

这篇关于检查 XML 元素是否有子元素或值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆