3

I’m working on a windows form application I’m trying to see if a certain xml node has child nodes, in the first lines of my code I used OpenFileDialog to open an xml file; in this case the xml sample below.

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

In my windows form application, I have an open button and a textbox1, the textbox1 is only used to display the address of the xml file and the open button sets everything in motion. Somewhere in the code I have the following lines of code:

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");
                        }
}

Here is what I don’t understand, I’m pointing to the author node which, as far as I can tell, does not have a child node but my code states that it does; if I were to erased Giada de Laurentiis then my code would say that the author node does not have

What Am I doing wrong?

R. Ben
  • 35
  • 6

2 Answers2

4

You could check whether there are any child nodes that don't have a NodeType of 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");
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • I'm happy to say the code works now with the changes you make to it, one last thing what is `x => x.NodeType != XmlNodeType.Text` doing? is that the lambda operator/expression? – R. Ben Feb 17 '17 at 13:50
  • Yes, it is a Predicate delegate represented by a lambda expression that filters the ChildNodes collection based on the NodeType: https://msdn.microsoft.com/en-us/library/bfcke1bz(v=vs.110).aspx – mm8 Feb 17 '17 at 14:13
0

It has a child node which is an instance of https://msdn.microsoft.com/en-us/library/system.xml.xmltext(v=vs.110).aspx XmlText. In the DOM there are different kind of nodes and the property HasChildNodes checks for any kind of child nodes (element, comment, processing instruction, text, cdata).

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110