C# XmlWriter 和无效的 UTF8 字符

标签 c# .net xml utf-8

我们创建了一个单元测试,它使用以下方法生成随机 UTF8 文本:

        private static Random _rand = new Random(Environment.TickCount);

        public static byte CreateByte()
        {
            return (byte)_rand.Next(byte.MinValue, byte.MaxValue + 1);
        }

        public static byte[] CreateByteArray(int length)
        {
            return Repeat(CreateByte, length).ToArray();
        }

        public static string CreateUtf8String(int length)
        {
            return Encoding.UTF8.GetString(CreateByteArray(length));
        }

        private static IEnumerable<T> Repeat<T>(Func<T> func, int count)
        {
            for (int i = 0; i < count; i++)
            {
                yield return func();
            }
        }

在将随机 UTF8 字符串发送到我们的业务逻辑时,XmlWriter 写入生成的字符串并可能会失败并显示错误:

Test method UnitTest.Utf8 threw exception: 
System.ArgumentException: ' ', hexadecimal value 0x0E, is an invalid character.

System.Xml.XmlUtf8RawTextWriter.InvalidXmlChar(Int32 ch, Byte* pDst, Boolean entitize)
System.Xml.XmlUtf8RawTextWriter.WriteAttributeTextBlock(Char* pSrc, Char* pSrcEnd)
System.Xml.XmlUtf8RawTextWriter.WriteString(String text)
System.Xml.XmlUtf8RawTextWriterIndent.WriteString(String text)
System.Xml.XmlWellFormedWriter.WriteString(String text)
System.Xml.XmlWriter.WriteAttributeString(String localName, String value)

我们希望支持传入任何可能的字符串,并且需要以某种方式对这些无效字符进行转义。

XmlWriter 已经对 &、<、> 等进行了转义,我们如何处理其他无效字符,如控制字符等?

PS - 让我知道我们的 UTF8 生成器是否有缺陷(我已经看到我不应该让它生成 '\0' 的地方)

最佳答案

XmlConvert Class有很多有用的方法(如 EncodeName、IsXmlChar 等)来确保您正在构建有效的 Xml。

关于C# XmlWriter 和无效的 UTF8 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393162/

相关文章:

javascript - 为什么 Jquery parseXML 不起作用?

c# - Asp.Net Core 2.1 ApiController 不会自动验证单元测试下的模型

c# - 在 IIS 中部署时,复选框在 TreeView 控件的节点上不可见

c# - 将字节数组从 C# 传递到 C++ (COM)

c# - 如何在 C# .Net 中使用 InsertOneAsync 将文档插入到 MongoDB 并返回相同的文档或其 ID

c# - NUnit:无法加载程序集 nunit.framework

java - 添加一个元素到根元素

Javascript xml 解析器 : how to get nodes that have ":" in the name

c# - 在 .NET 2.0 中实现 BDD/TDD 的最佳方式是什么?

c# - 在 DataView 过滤器中使用聚合函数