繁体   English   中英

的XMLNode。 HasChild将InnerText视为子节点

[英]XMLNode. HasChild considers InnerText as a child node

我正在开发一个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窗体应用程序中,我有一个打开按钮和一个textbox1,textbox1仅用于显示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");
}

它有一个子节点,它是https://msdn.microsoft.com/en-us/library/system.xml.xmltext(v=vs.110).aspx XmlText一个实例。 在DOM中有不同类型的节点,属性HasChildNodes检查任何类型的子节点(元素,注释,处理指令,文本,cdata)。

暂无
暂无

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

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