Question

I am Adding Some X elements to Root element using (We are using .Net 2.0)

xnode.AppendChild(parentINode);
xnode.AppendChild(config.CreateTextNode("\r\n"));
//then removeing all added elements using 
xnode.ParentNode.RemoveChild(xnode);

This Will Add a whitespace, I want to remove whitespace that were addedd by adding elements, while removing the childnode.

My original file looks as below:

  <c123:Images State="ARASU">
  <!-- Names-Images -->
 </c123:Images>

We will Be adding some elements to it :

    <c123:Images State="ARASU">
     <!-- Names-Images -->
     <Name place=123>
     <Name place=1234>
     </c123:Images>

Then we will delete elements :then it looks as below

   <c123:Images State="ARASU">
   <!-- Names-Images -->


    </c123:Images>

Here we are getting number of white spaces equal to number of elements added, we want to remove/Avoid the white space created after deleting child nodes. Thanks & Regards,
Channabasappa M

Was it helpful?

Solution

You can use this extension method :

    public static void RemoveEmptyElementsAndWhiteSpaces(this XDocument document)
    {
        if(null == document)
            throw new ArgumentNullException("document");

        document.Descendants()
            .Where(e => e.IsEmpty || string.IsNullOrWhiteSpace(e.Value))
            .Remove();
    }

Edit : if you are using the XmlDocument class, maybe you can set the PreserveWhiteSpace property to false ?

OTHER TIPS

I Did Just Traversing to XML tag then Removed whitespace with checking

    //Removing whitespace created 

   if (xnode.NextSibling != null && xnode.NextSibling.NodeType == XmlNodeType.Whitespace)
      {
            xnode.ParentNode.RemoveChild(xnode.NextSibling);
      }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top