I am creating some XML files and I ran into a problem. I have tried to find other answers online but they have not helped.
I would like to remove the parent and child in a XML if all the children of said parent is empty. For example:
<client>
<name>test</name>
<adresses>
<address>
<adressname>test1</adressname>
<adressplace>somewhere</adressplace>
</address>
<address>
<adressname />
<adressplace />
</address>
</adresses>
</client>
should become:
<client>
<name>test</name>
<adresses>
<address>
<adressname>test1</adressname>
<adressplace>somewhere</adressplace>
</address>
</adresses>
</client>
The XML has a lot of tags that will be removed on different levels.
Does anyone have a good idea how to tackle this problem?
Please use the following function.
private void RemoveNodesWithEmptyValue(XmlNode node)
{
if (node.ChildNodes.Count == 0)
{
if (node.Value == null)
{
node.ParentNode.RemoveChild(node);
}
}
else
{
int nCount = node.ChildNodes.Count;
for (int i = nCount - 1; i >= 0; i--)
{
RemoveNodesWithEmptyValue(node.ChildNodes[i]);
}
if (node.ChildNodes.Count == 0)
{
if (node.Value == null)
{
node.ParentNode.RemoveChild(node);
}
}
}
}
With the following code, you can get the desired result.
// input xml string
string strXml = "...";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strXml);
RemoveNodesWithEmptyValue(xmlDoc.DocumentElement);
string result = xmlDoc.OuterXml;
I share a full source project.