Search code examples
c#xmlxmldocumentxmlnode

How do you remove blank lines from an XML document or node using C#?


I want all the blank lines to be removed in the XML below before writing it to document. It may help to know that I used the .DeleteSelf() method of the XPathNavigator class to get rid of the unwanted nodes before (and that only leaves empty lines).

    <Person xmlns="http://someURI.com/something">
      <FirstName>Name1</FirstName>











       <MiddleName>Name2</MiddleName>


       <LastName>Name3</LastName>




     </Person>

Solution

  • I'd suggest to use XDocument class:

    1. method:

    string xcontent = @" strange xml content here ";
    XDocument xdoc = XDocument.Parse(xcontent);
    xdoc.Save("FullFileName.xml");
    

    2. method:

    XmlReader rdr = XmlReader.Create(new StringReader(xcontent));
    XDocument xdoc = XDocument.Load(rdr);
    xdoc.Save("FullFileName.xml");
    

    returns:

    <Person xmlns="http://someURI.com/something">
      <FirstName>Name1</FirstName>
      <MiddleName>Name2</MiddleName>
      <LastName>Name3</LastName>
    </Person>
    

    Msdn documentation: https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument%28v=vs.110%29.aspx