C#:XmlTextWriter.WriteElementString 在空字符串上失败?
我正在使用 XmlTextWriter
及其 WriteElementString
方法,例如:
XmlTextWriter writer = new XmlTextWriter("filename.xml", null);
writer.WriteStartElement("User");
writer.WriteElementString("Username", inputUserName);
writer.WriteElementString("Email", inputEmail);
writer.WriteEndElement();
writer.Close();
预期的 XML 输出为:
<User>
<Username>value</Username>
<Email>value</Email>
</User>
但是,如果例如 inputEmail 为空,则我得到的结果 XML 如下:
<User>
<Username>value</Username>
<Email/>
</User>
而我希望它是:
<User>
<Username>value</Username>
<Email></Email>
</User>
我做错了什么? 有没有办法使用 XmlTextWriter
以简单的方式实现我的预期结果?
I'm using XmlTextWriter
and its WriteElementString
method, for example:
XmlTextWriter writer = new XmlTextWriter("filename.xml", null);
writer.WriteStartElement("User");
writer.WriteElementString("Username", inputUserName);
writer.WriteElementString("Email", inputEmail);
writer.WriteEndElement();
writer.Close();
The expected XML output is:
<User>
<Username>value</Username>
<Email>value</Email>
</User>
However, if for example inputEmail is empty, the result XML I get as as follows:
<User>
<Username>value</Username>
<Email/>
</User>
Whereas I would expect it to be:
<User>
<Username>value</Username>
<Email></Email>
</User>
What am I doing wrong? Is there a way to achieve my expected result in a simple way using XmlTextWriter
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的输出是正确的。 没有内容的元素应该写成
。您可以通过调用 WriteFullEndElement() 强制使用完整标记,
当 inputEmail 为空时,它将输出
。如果您想多次执行此操作,您可以创建一个扩展方法:
然后您的代码将变为:
Your output is correct. An element with no content should be written as
<tag/>
.You can force the use of the full tag by calling WriteFullEndElement()
That will output
<Email></Email>
when inputEmail is empty.If you want to do that more than once, you could create an extension method:
Then your code would become:
它不会失败
只是
的快捷方式It doesn't fail
<Tag/>
is just a shortcut for<Tag></Tag>
您的代码应该是:
这可以避免出现异常时的资源泄漏,并使用正确的方法创建 XmlReader(自 .NET 2.0 起)。
Your code should be:
This avoids resource leaks in case of exceptions, and uses the proper way to create an XmlReader (since .NET 2.0).
把它留在这里以备不时之需; 因为上面的答案都没有为我解决这个问题,或者看起来有点矫枉过正。
诀窍是设置XmlWriterSettings.Indent = true并将其添加到XmlWriter。
编辑:
或者,您也可以使用
XmlWriterSettings
来代替添加。Leaving this here in case someone needs it; since none of the answers above solved it for me, or seemed like overkill.
The trick was to set the XmlWriterSettings.Indent = true and add it to the XmlWriter.
Edit:
Alternatively you can also use
instead of adding an
XmlWriterSettings
.尝试用另一种方法解决这个问题,可能需要优化。
Tried solving this with another approach, might need optimization.