C# 删除XElement结束标记中的空白
我正在构建的一些XML如下所示:C# 删除XElement结束标记中的空白,c#,xml,xelement,C#,Xml,Xelement,我正在构建的一些XML如下所示: <actionitem actiontaken="none" target="0" targetvariable="0"> <windowname>Popup Window</windowname> <windowposx>-1</windowposx> <windowposy>-1</windowposy> <windowwidth>-1</w
<actionitem actiontaken="none" target="0" targetvariable="0">
<windowname>Popup Window</windowname>
<windowposx>-1</windowposx>
<windowposy>-1</windowposy>
<windowwidth>-1</windowwidth>
<windowheight>-1</windowheight>
<noscrollbars>false</noscrollbars>
<nomenubar />
<notoolbar />
<noresize />
<nostatus />
<nolocation />
<browserWnd />
</actionitem>
var lines = File.ReadAllLines("path");
for(int i=0;i<lines.Length;i++)
{
if (lines[i].Contains(" />")) lines[i] = lines[i].Replace(" />", "/>");
}
File.WriteAllLines("path", lines);
但当我运行该程序时,会收到以下错误消息:
Non white space characters cannot be added to content.
那么,有人知道一旦我构建了XML文档,我如何删除空白吗?我会将
XML
内容读为文本,然后替换这样的空白:
<actionitem actiontaken="none" target="0" targetvariable="0">
<windowname>Popup Window</windowname>
<windowposx>-1</windowposx>
<windowposy>-1</windowposy>
<windowwidth>-1</windowwidth>
<windowheight>-1</windowheight>
<noscrollbars>false</noscrollbars>
<nomenubar />
<notoolbar />
<noresize />
<nostatus />
<nolocation />
<browserWnd />
</actionitem>
var lines = File.ReadAllLines("path");
for(int i=0;i<lines.Length;i++)
{
if (lines[i].Contains(" />")) lines[i] = lines[i].Replace(" />", "/>");
}
File.WriteAllLines("path", lines);
var lines=File.ReadAllLines(“路径”);
对于(int i=0;i我不知道如何使用XElement
,最好的选择是将Xml
作为文本读取,但为了避免不必要的多余字符串分配,请通过字符串生成器执行:
var element = new XElement...;
var stringBuilder = new StringBuilder();
using (var stringWriter = new StringWriter(stringBuilder))
{
element.Save(stringWriter);
}
stringBuilder.Replace(" />", "/>");
var xml = stringBuilder.ToString();
Console.WriteLine(xml);
任何执行.ToString().Replace()
的方法在内存使用方面的成本都要高得多
客户的评论令人担忧的是,听起来他们有一个自制的xml解析器,这不是很好,自动关闭标记中的空白不应该有什么区别。是的,就客户(国防部)而言,他们“已经这样做很长时间了”这需要国会通过法案才能让他们修改。我喜欢这样,因为我可以在内存中浏览文档。让我试试这个,看看它对我有什么作用。我可以尝试修改它,这样我就可以在文档在内存中且尚未保存在文件中时循环浏览文档。我现在就试试。谢谢,塞尔曼!尽管如此我没有选择你的答案,我非常感谢你花时间和精力帮助我。@KevinJ没关系。如果我能帮忙,我很高兴:)