我们创建了一个单元测试,它使用以下方法生成随机 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/