gpt4 book ai didi

c# - XmlTextWriter 错误地写入控制字符

转载 作者:可可西里 更新时间:2023-11-01 08:08:01 25 4
gpt4 key购买 nike

.NET 的 XmlTextWriter 创建无效的 xml 文件。

在 XML 中,一些控制字符是允许的,例如“水平制表符”( ),但其他的则不允许,例如“垂直制表符”( )。 (参见 spec。)

我有一个字符串,其中包含 XML 中不允许的 UTF-8 控制字符。
尽管 XmlTextWriter 对字符进行了转义,但生成的 XML 当然仍然无效。

如何确保 XmlTextWriter 永远不会生成非法的 XML 文件?

或者,如果无法使用 XmlTextWriter 执行此操作,我如何从字符串中去除 XML 中不允许的特定控制字符?

示例代码:

using (XmlTextWriter writer =
new XmlTextWriter("test.xml", Encoding.UTF8))
{
writer.WriteStartDocument();
writer.WriteStartElement("Test");
writer.WriteValue("hello \xb world");
writer.WriteEndElement();
writer.WriteEndDocument();
}

输出:

<?xml version="1.0" encoding="utf-8"?><Test>hello &#xB; world</Test>

最佳答案

此行为文档隐藏在 documentation of the WriteString method 中但听起来它适用于整个类(class)。

The default behavior of an XmlWriter created using Create is to throw an ArgumentException when attempting to write character values in the range 0x-0x1F (excluding white space characters 0x9, 0xA, and 0xD). These invalid XML characters can be written by creating the XmlWriter with the CheckCharacters property set to false. Doing so will result in the characters being replaced with numeric character entities (&#0; through &#0x1F). Additionally, an XmlTextWriter created with the new operator will replace the invalid characters with numeric character entities by default.

所以看起来您最终写入了无效字符,因为您使用的是 XmlTextWriter 类。更好的解决方案是使用 XmlWriter Class相反。

关于c# - XmlTextWriter 错误地写入控制字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8256010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com