c# - XML 节点。 HasChild 将 InnerText 视为子节点

标签 c# xml xmlnode

我正在开发一个 Windows 窗体应用程序,我试图查看某个 xml 节点是否有子节点,在我的代码的第一行中,我使用 OpenFileDialog 打开一个 xml 文件;在这种情况下,下面的 xml 示例。

<bookstore>
   <book category="cooking">
     <title lang="en">Everyday Italian</title>
     <author>Giada De Laurentiis</author>
     <year>2005</year>
     <price>30.00</price>
   </book>
</bookstore>

在我的 windows 窗体应用程序中,我有一个打开按钮和一个文本框 1,文本框 1 仅用于显示 xml 文件的地址,打开按钮设置所有内容。在代码的某处,我有以下代码行:

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;

//other lines of code
private void Open_XML_button_Click(object sender, EventArgs e)
{
//other lines of code
XmlDocument xmldoc = new XmlDocument();
string XML_Location;

XML_Location = textBox1.Text;
xmldoc.Load(XML_Location);

string category = "category = 'cooking'";
XmlNode test1 = xmldoc.SelectSingleNode(string.Format("/bookstore/book[@{0}]/author", category));

if (test1.HasChildNodes == true)
                        {
                            MessageBox.Show("It has Child nodes");
                        }

                        else
                        {
                            MessageBox.Show("it does not have Child nodes");
                        }
}

这是我不明白的地方,我指的是作者节点,据我所知,它没有子节点,但我的代码声明它有;如果我要删除 Giada de Laurentiis,那么我的代码会说作者节点没有

我做错了什么?

最佳答案

您可以检查是否有任何子节点的 NodeTypeXmlNodeType.Text:

string category = "category = 'cooking'";
XmlNode test1 = xmldoc.SelectSingleNode(string.Format("/bookstore/book[@{0}]/author", category));
if (test1.ChildNodes.OfType<XmlNode>().Any(x => x.NodeType != XmlNodeType.Text))
{
    MessageBox.Show("It has Child nodes");
}
else
{
    MessageBox.Show("it does not have Child nodes");
}

关于c# - XML 节点。 HasChild 将 InnerText 视为子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42284206/

相关文章:

c# - 如何为 IDisposable 类型使用自定义生成器?

java - 如何使不同子类的实例具有其公共(public)父类的相同实例?

c# - 如果客户端进程在事务开始后被终止,数据库表将保持锁定状态

c# - 使用 WCF 将类序列化为由 xsd.exe 生成的 JSON

HTML 列表 - 每个循环的 XSLT 多重嵌套

c# - 使用 System.Xml.XmlDocument 时是否可以从 System.Xml.XmlNode 获取行号/位置?

c# - 如何在 C# 中仅引发 1 个计时器事件?

xml - 如何使用 vbscript 删除 XML 文件中的节点?

c# - 如何从多个嵌套级别发生的 XMLDocument 中删除 XMLNode

xml - XML 中的元素和节点有什么区别?