简体   繁体   English

删除XElement结束标记中的空格

[英]Removing whitespace in XElement closing tag

I have some XML that I am building that looks like this: 我有一些我正在构建的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>

This XML has to be to the exact specifications of the client, meaning I can't have a whitespace in the closing tag. 这个XML必须符合客户端的确切规范,这意味着我在结束标记中不能有空格。 I know that MSDN says this: 我知道MSDN这样说:

When writing an empty element, an additional space is added between tag name and the closing tag, for example . 编写空元素时,例如,在标记名称和结束标记之间添加了一个额外的空格。 This provides compatibility with older browsers. 这提供了与旧浏览器的兼容性。

But, the client won't/can't budge on this. 但是,客户不会/不能让步。 So, I thought I could try something like this to remedy the problem: 所以,我想我可以尝试这样的方法来解决问题:

xelement.ReplaceWith(" />", "/>");

But when I run the program, I get this error message: 但是,当我运行该程序时,我收到此错误消息:

Non white space characters cannot be added to content.

错误信息

So, does anyone know how I can remove that white space once I've built the XML document? 那么,有没有人知道我在构建XML文档后如何删除该空格?

I don't know of a way to do it using an XElement , the best option will be to read the Xml as text but to avoid unnecessary excess string allocation, do it via a string builder: 我不知道使用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);

Any method which does a .ToString().Replace() is going to be far more costly in terms of memory usage. 任何执行.ToString().Replace()方法在内存使用方面都会花费更多。

The worrying thing about your client's comment is that it sounds like they have a home made xml parser which isn't very good, the whitespace in a self closing tag should not make a difference. 关于客户评论的令人担忧的事情是,听起来他们有一个自制的xml解析器并不是很好,自闭标签中的空白不应该有所作为。

I would read XML content as text then Replace the spaces like this: 我会将XML内容读作文本然后Replace的空格:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM