我正在开发一个 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,那么我的代码会说作者节点没有
我做错了什么?
最佳答案
您可以检查是否有任何子节点的 NodeType
为 XmlNodeType.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/