【发布时间】:2011-05-22 13:05:34
【问题描述】:
我们创建了一个单元测试,它使用以下方法生成随机 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')
【问题讨论】: