Search code examples
c#sql-serverxmlsql-server-2008xmlreader

XmlReader and InvalidCharacter


I am using SqlCommand.ExecuteXmlReader() to Execute an SqlCommand with FOR XML AUTO, ELEMENTS

Now, there is a column which contains for xml invalid characters (like 0x1F). When I read now the result of the XmlReader with

using (var xmlReader = command.ExecuteXmlReader()) {
xmlReader.Read();
    while (xmlReader.ReadState != ReadState.EndOfFile) {
        try {
            sb.Append(xmlReader.ReadOuterXml());
        } catch(Exception e) {
            log.Error("Error in xmlReader.ReadOuterXml()", e);
        }
    }
}

I get the Exception "Invalid Character" at xmlreader.ReadOuterXml() when It read the Invalid Character. Does anybody know a Workaround how I can solve this problem?


Solution

  • You could surround your XML data with <![CDATA[Data]]>, like this

    <SomeNode><![CDATA[0x1F]]></SomeNode>
    

    OR you can use XmlConvert to Encode/Decode the XML data. Look here for mor info: http://msdn.microsoft.com/en-us/library/35577sxd%28v=VS.100%29.aspx