Hi,
I recently had a problem with one of my XPath expressions which led me
to believe there might be a bug in XmlNode, although it could be by
design since I didn't find anything in the KB.
Consider the the code appended below. The function CleanEmptyElements
removes all empty elements from the document using a XPath expression.
As you will notice in the code, I add two empty elements. If you check
the resulting testXml.xml file, the "SpecialEmptyElement" element,
though emtpy is still present.
The only special thing about it is that I assign a null string to the
InnerText property of its node. As far as I know, this shouldn't make a
difference, it should still be an empty element which is confirmed by
the output of the file.
However, if you step through the code with the debugger, you will notice
that as soon as I assign the null string, a new node gets added and the
HasChildNodes property gets set to true.
If you try the same with the InnerXml property, you get the behavior I
was expecting, which is that nothing happens. So there seems to be an
inconsistency here unless I'm mistaken.
So, is this a bug or normal behavior?
Thanks
using System;
using System.Xml;
namespace EmptyElement
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
XmlDocument myDoc = new XmlDocument();
XmlNode currentNode = myDoc.CreateElement("Root");
currentNode = myDoc.AppendChild(currentNode);
XmlNode tempNode = myDoc.CreateElement
("EmptyElement");
currentNode.AppendChild(tempNode);
tempNode = myDoc.CreateElement
("SpecialEmptyElement");
tempNode.InnerText = null;
currentNode.AppendChild(tempNode);
CleanEmptyElements(myDoc);
myDoc.Save("c:\\testXml.xml");
}
static void CleanEmptyElements (XmlDocument myDoc)
{
int i;
XmlNodeList elementsToRemove;
do
{
elementsToRemove = myDoc.SelectNodes("//*[not
(node())]");
for (i = 0; i < elementsToRemove.Count; i++)
{
elementsToRemove
[i].ParentNode.RemoveChild(elementsToRemove[i]);
}
}
while(elementsToRemove.Count > 0);
}
}
}