如何停止的XMLReader抛出无效的XML字符异常 [英] How to stop XMLReader throwing Invalid XML Character Exception

查看:315
本文介绍了如何停止的XMLReader抛出无效的XML字符异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一些XML:



<键>我的标签< /键><价值>我的标记值和放大器;#的xB;我的无效字符< /值>



和一个XMLReader:

  {
>而(reader.Read())
{
//做我的事
}
}

我已经实现了从这里但CleanInvalidCharacters方法的。&放大器; #xB尚未编码它不会删除



该错误信息是应reader.Read抛出();与异常行:




十六进制值0x0B中,是一个无效字符



解决方案

的问题是,你不必XML - 你有一些字符串,它肯定看起来像XML但遗憾的是并没有真正出线。幸运的是,你可以告诉的XmlReader 更宽松:



<预类=郎-CS prettyprint-覆盖> 使用(读者的XmlReader = XmlReader.Create(新StringReader(XML),新的XmlReaderSettings {CheckCharacters = FALSE}))
{
,而(reader.Read())
{
//做我的事
}
}

请注意,你仍然会结束与,系列化的时候,可能会进一步产生问题的路线XML,所以你不妨明算账呢,你正在阅读它的字符进行过滤。


So I have some XML:

<key>my tag</key><value>my tag value &#xB;and my invalid Character</Value>

and an XMLReader:

using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
     while (reader.Read())
     {
         //do my thing
     }
}

I have implemented the CleanInvalidCharacters method from here but as the "&#xB" is not yet encoded it doesn't get removed.

The error is being thrown at the reader.Read(); line with exception:

hexadecimal value 0x0B, is an invalid character.

解决方案

The problem is that you don't have XML -- you have some string that sure looks like XML but unfortunately doesn't really qualify. Fortunately you can tell XmlReader to be more lenient:

using (XmlReader reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings { CheckCharacters = false }))
{
     while (reader.Read())
     {
         //do my thing
     }
}

Note that you will still end up with XML that, when serialized, might produce problems further down the line, so you may wish to filter the characters out afterwards anyway as you're reading it.

这篇关于如何停止的XMLReader抛出无效的XML字符异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆