我希望在将其写入文档之前,在下面的XML中删除所有空白行。知道我使用XPathNavigator类的.DeleteSelf()方法来摆脱之前的不需要的节点(并且只留下空行)可能会有所帮助。
<Person xmlns="http://someURI.com/something">
<FirstName>Name1</FirstName>
<MiddleName>Name2</MiddleName>
<LastName>Name3</LastName>
</Person>
答案 0 :(得分: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
答案 1 :(得分: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>