2016-03-08 93 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