0

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>
user2840682
  • 381
  • 2
  • 11
  • 23
  • 1
    Have you tried to load such of content into `XDocument` then to save it as xml file? – Maciej Los Mar 08 '16 at 21:47
  • Refer to this post http://stackoverflow.com/a/6480081/1513471 – believe me Mar 08 '16 at 21:49
  • Possible duplicate of [What is the simplest way to get indented XML with line breaks from XmlDocument?](http://stackoverflow.com/questions/203528/what-is-the-simplest-way-to-get-indented-xml-with-line-breaks-from-xmldocument) – har07 Mar 09 '16 at 00:42

2 Answers2

1

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

Maciej Los
  • 8,468
  • 1
  • 20
  • 35
0

Can also do line by line reading and writing.

            string line = string.Empty;
            using (StreamReader file_r = new System.IO.StreamReader("HasBlankLines.xml"))
            {
                using (StreamWriter file_w = new System.IO.StreamWriter("NoBlankLines.xml"))
                {
                    while ((line = file_r.ReadLine()) != null)
                    {
                        if (line.Trim().Length > 0)
                            file_w.WriteLine(line);
                    }
                }
            }

Outputs:

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