Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLNode. HasChild considers InnerText as a child node

Tags:

c#

xml

xmlnode

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?

like image 967
R. Ben Avatar asked Apr 16 '26 23:04

R. Ben


1 Answers

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");
}
like image 157
mm8 Avatar answered Apr 18 '26 11:04

mm8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!