mysql 正则 unicode_Unicode正则表达式; 无效的XML字符

如果xml中存在十六进制代码,则上述解决方案对我不起作用。 例如

以下代码将中断:

string xmlFormat = "{0}";

string invalid = " ";

string xml = string.Format(xmlFormat, invalid);

xml = Regex.Replace(xml, @"[\x01-\x08\x0B\x0C\x0E\x0F\u0000-\u0008\u000B\u000C\u000E-\u001F]", "");

XDocument.Parse(xml);

它返回:

XmlException:”(十六进制值0x08)是无效字符。 第1行,位置14。

以下是经过改进的正则表达式,并修复了上述问题:

&#x([0-8BCEFbcef] | 1 [0-9A-Fa-f]); | [\ x01- \ x08 \ x0B \ x0C \ x0E \ x0F \ u0000- \ u0008 \ u000B \ u000C \ u000E- \ [u001F]

这是对前300个unicode字符的单元测试,并验证仅删除了无效字符:

[Fact]

public void validate_that_RemoveInvalidData_only_remove_all_invalid_data()

{

string xmlFormat = "{0}";

string[] allAscii = (Enumerable.Range('\x1', 300).Select(x => ((char)x).ToString()).ToArray());

string[] allAsciiInHexCode = (Enumerable.Range('\x1', 300).Select(x => "" + (x).ToString("X") + ";").ToArray());

string[] allAsciiInHexCodeLoweCase = (Enumerable.Range('\x1', 300).Select(x => "" + (x).ToString("x") + ";").ToArray());

bool hasParserError = false;

IXmlSanitizer sanitizer = new XmlSanitizer();

foreach (var test in allAscii.Concat(allAsciiInHexCode).Concat(allAsciiInHexCodeLoweCase))

{

bool shouldBeRemoved = false;

string xml = string.Format(xmlFormat, test);

try

{

XDocument.Parse(xml);

shouldBeRemoved = false;

}

catch (Exception e)

{

if (test != "

{

shouldBeRemoved = true;

}

}

int xmlCurrentLength = xml.Length;

int xmlLengthAfterSanitize = Regex.Replace(xml, @"([0-8BCEF]|1[0-9A-F]);|[\u0000-\u0008\u000B\u000C\u000E-\u001F]", "").Length;

if ((shouldBeRemoved && xmlCurrentLength == xmlLengthAfterSanitize) //it wasn't properly Removed

||(!shouldBeRemoved && xmlCurrentLength != xmlLengthAfterSanitize)) //it was removed but shouldn't have been

{

hasParserError = true;

Console.WriteLine(test + xml);

}

}

Assert.Equal(false, hasParserError);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值