Reputation: 35
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?
Upvotes: 3
Views: 1848
Reputation: 169150
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");
}
Upvotes: 4
Reputation: 167436
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).
Upvotes: 0