Resolved Parent Node format issue after deleting/removing all child nodes

ram_rocks

Active member
Joined
Jun 14, 2021
Messages
27
Programming Experience
1-3
Hello,

I have written below code to delete all child nodes and after deleting it the parent node format is not in expected way.
C#:
XmlNodeList packgList = _xd.GetElementsByTagName("Package");

foreach (XmlNode pkg in packgList)
{
    foreach (XmlNode test in pkg.ChildNodes)
    {
       if (test.Name == "Test")
       {
          for (int i = test.ChildNodes.Count - 1; i >= 0; i--)
          {
             test.RemoveChild(test.ChildNodes[i]);
          }
       }
    }
}

my input is
C#:
<Package>
    <name>A</name>
    <Test>
      <employee1>
        <name>xcvb</name>
        <details>asdasd</details>
      </employee1>
      <employee2>
        <name>xcvb</name>
        <details>asdasd</details>
      </employee2>
    </Test>
</Package>

my output is which is not in expected way
C#:
<Package>
    <name>A</name>
    <Test/>
</Package>

so here in output I am expecting like
C#:
<Package>
    <name>A</name>
    <Test>
    </Test>
</Package>
 
If it really is an issue (it should not be, because the first is valid XML and has exactly the same meaning as the second) then you could try the following, although I'm not 100% sure it will work:
C#:
for (int i = test.ChildNodes.Count - 1; i >= 0; i--)
{
    test.RemoveChild(test.ChildNodes[i]);
}

test.InnerText = string.Empty;
I think that your code will leave the InnerText equal to null and that causes a self-closing tag to be written but having an empty value instead will produce separate opening and closing tags.

That said, it might also be affected by how you're actually writing the final XML out, but you haven't shown us that part so who knows.
 
Back
Top Bottom