Help with XmlNode - HasChildNodes always returns true even no immediate child exists

R

RJN

Hi

I have to read an xml and add the node elements into a hashtable with
nodename as key and nodetext as value. If the selected node has
childnodes, then value should go as an array.

for eg.,

<Root>
<mysection>
<logroot>e:\temp</logroot>
<outputdir>
<dir1>e:\temp1</dir1><dir2>e:\temp2</dir2>
</outputdir>
</mysection>
<myanothersection></myanothersection>
</Root>

I would first search for "Root/mysection". Now since logroot doesn't
have further childnodes, I would like to add to the hashtable "logroot"
as key and "e:\temp" as value. The next node outputdir has 2 child nodes
dir1 and dir2. I would like to create a string array for the values of
dir1 and dir2 and add to the hashtable "outputdir" as key and the array
as value.

The following code is not working for me.

string strXml =
"<Root><mysection><logroot>e:\\temp</logroot><outputdir><dir1>e:\\temp1<
/dir1><dir2>e:\\temp2</dir2></outputdir></mysection></Root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strXml);
XmlNode xmlSection = xmlDoc.SelectSingleNode("Root/mysection");
Hashtable htValues = new Hashtable();
foreach(XmlNode node in xmlSection.ChildNodes)
{
if(node.HasChildNodes)
{
string[] str = new string[node.ChildNodes.Count];
for(int i=0;i<node.ChildNodes.Count;i++)
str = node.ChildNodes.InnerText;
htValues.Add(node.Name, str);
}
else
htValues.Add(node.Name, node.InnerText);

}
I always get node.HasChildNodes as true even though the node doesn't
have further child nodes. Because of this, I end up adding an array as
value for every node. If the values inside the node is empty then it is
working fine.

Any help is appreciated.

Regards

rjn
 
J

Jon Skeet [C# MVP]

RJN said:
I have to read an xml and add the node elements into a hashtable with
nodename as key and nodetext as value. If the selected node has
childnodes, then value should go as an array.

for eg.,

<Root>
<mysection>
<logroot>e:\temp</logroot>
<outputdir>
<dir1>e:\temp1</dir1><dir2>e:\temp2</dir2>
</outputdir>
</mysection>
<myanothersection></myanothersection>
</Root>

I would first search for "Root/mysection". Now since logroot doesn't
have further childnodes, I would like to add to the hashtable "logroot"
as key and "e:\temp" as value.

logroot *does* have a child node - it has a text node. It doesn't have
any child *elements*, but that's not the same thing.

Hope that helps - if not, I'll try to give some code later on. Time to
put my son to bed first though...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top