XMLNode。 HasChild认为InnerText作为一个子节点
问题描述:
我正在一个Windows窗体应用程序我想看看如果某个XML节点有子节点,在我的代码的第一行我用OpenFileDialog来打开一个XML文件;在这种情况下,下面的xml示例。XMLNode。 HasChild认为InnerText作为一个子节点
<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,那么我的代码会说作者节点没有
我在做什么错了?
答
你可以检查是否有没有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");
}
答
它有一个子节点,它是https://msdn.microsoft.com/en-us/library/system.xml.xmltext(v=vs.110).aspxXmlText
的一个实例。在DOM中有不同类型的节点,属性HasChildNodes
检查任何类型的子节点(元素,注释,处理指令,文本,cdata)。
我很高兴地说,现在的代码工作与你做的一些修改,最后一件事什么是'x => x.NodeType!= XmlNodeType.Text'在做什么?是lambda运算符/表达式? –
是的,它是一个谓词由lambda表达式表示的代理,该表达式基于NodeType过滤ChildNodes集合:https://msdn.microsoft.com/en-us/library/bfcke1bz(v=vs.110).aspx –
mm8