The structure of my XML using XElement looks like this. I am using XElement in XDocument
<?xml version='1.0' encoding='UTF-8'?>
<return xmlns:rmas="" xmlns:xsi="" xsi:noNamespaceSchemaLocation="">
<header>
[...]
</header>
<body>
<scheme>
[...]
<data>
<serial-no>1</serial-no>
<employment>1</employment>
<code>1234</code>
</data>
<data />
<data />
</scheme>
<scheme>
[...]
<data>
<serial-no>1</serial-no>
<employment>1</employment>
<code>1234</code>
</data>
<data />
<data />
</scheme>
<scheme>
[...]
<data>
<serial-no>1</serial-no>
<employment>1</employment>
<code>1234</code>
</data>
<data />
<data />
</scheme>
</body>
</return>
I'd like to remove all data elements with no child elements i.e
<data />
elements. Here's my code
foreach (XElement scheme in doc.Descendants("scheme"))
{
//copy an existing node as template for new data node.
XElement newData = XElement.Parse(scheme.Element("data").ToString());
newData.Element("serial-no").SetValue("abc1234");
newData.Element("employment").SetValue("PUZAD-452");
newData.Element("code").SetValue(codeValue);
XElement newData2 = XElement.Parse(scheme.Element("data").ToString());
newData2.Element("serial-no").SetValue("abc1234");
newData2.Element("employment").SetValue("PUZAD-452");
newData2.Element("code").SetValue(codeValue);
XElement newData3 = XElement.Parse(scheme.Element("data").ToString());
newData3.Element("serial-no").SetValue("abc1234");
newData3.Element("employment").SetValue("PUZAD-452");
newData3.Element("code").SetValue(codeValue);
if (getGlobalScheme1 == "1111")
{
if ((string)(scheme.Descendants("code").First()) == "1111")
{
newData2.RemoveAll();
newData3.RemoveAll();
}
scheme.Add(newData);
}
if (getGlobalScheme2 == "2222")
{
if ((string)(scheme.Descendants("code").First()) == "2222")
{
newData.RemoveAll();
newData3.RemoveAll();
}
scheme.Add(newData2);
}
if (getGlobalScheme3 == "3333")
{
if ((string)(scheme.Descendants("code").Last()) == "3333")
{
newData.RemoveAll();
newData2.RemoveAll();
}
scheme.Add(newData3);
}
}
How do i achieve my goal of removing the
<data />
elements with no child elements. I've been cracking my head around this but to no avail.