【问题标题】:XMLNode. HasChild considers InnerText as a child nodeXML 节点。 HasChild 将 InnerText 视为子节点
【发布时间】:2017-07-06 04:04:18
【问题描述】:

我正在开发一个 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,那么我的代码会说作者节点没有

我做错了什么?

【问题讨论】:

    标签: c# xml xmlnode


    【解决方案1】:

    您可以检查是否有没有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");
    }
    

    【讨论】:

    • 我很高兴地说代码现在可以与您对其所做的更改一起使用,最后一件事 x =&gt; x.NodeType != XmlNodeType.Text 在做什么?那是 lambda 运算符/表达式吗?
    • 是的,它是一个 Predicate 委托,由一个基于 NodeType 过滤 ChildNodes 集合的 lambda 表达式表示:msdn.microsoft.com/en-us/library/bfcke1bz(v=vs.110).aspx
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2012-04-05
      • 2011-02-09
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 2014-12-15
      相关资源
      最近更新 更多