2016-03-08 94 views
-1

我希望在寫入文檔之前,在下面的XML中刪除所有空行。這可能有助於瞭解我使用XPathNavigator類的.DeleteSelf()方法在(以及僅留下空行)之前擺脫了不需要的節點。如何從使用C#的XML文檔或節點中刪除空白行?

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











     <MiddleName>Name2</MiddleName> 


     <LastName>Name3</LastName> 




    </Person> 
+1

你試圖加載這樣的內容轉換成'XDocument'然後將其保存爲XML文件? –

+0

參考這篇文章http://stackoverflow.com/a/6480081/1513471 –

+0

可能重複[什麼是最簡單的方法來從XmlDocument獲取縮進XML換行符?](http://stackoverflow.com/questions/) 203528/what-is-the-simple-way-to-in-indented-xml-with-line-breaks-from-xmldocument) – har07

回答

1

我建議使用XDocument類:

1.方法:

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

2.方法:

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

回報:

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

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

0

還可以通過在線閱讀和寫作做線。

  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); 
        } 
       } 
      } 

輸出:

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

這裏假定沒有一個元素的值是一個文本節點,其中有空行。 – StriplingWarrior