How to stop XMLReader throwing Invalid XML Character Exception

谁都会走 提交于 2019-12-09 17:58:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26357994/how-to-stop-xmlreader-throwing-invalid-xml-character-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!