tags:

views:

246

answers:

1

I am trying to validate my xml against it's xsd and getting the error invalid character in given encoding. The code I use to validate is below:

private static void ValidatingProcess(string XSDPath, string xml)
    {
        MemoryStream stream =
            new MemoryStream(ASCIIEncoding.Default.GetBytes(xml));

        using (StreamReader SR = new StreamReader(XSDPath))
        {
            XmlSchema Schema = XmlSchema.Read(SR, ReaderSettings_ValidationEventHandler);
            XmlReaderSettings ReaderSettings = new XmlReaderSettings();
            ReaderSettings.ValidationType = ValidationType.Schema;
            ReaderSettings.Schemas.Add(Schema);

            ReaderSettings.ValidationEventHandler += ReaderSettings_ValidationEventHandler;
            XmlReader objXmlReader = XmlReader.Create(stream, ReaderSettings);

            bool notDone = true;
            while (notDone)
            {
                notDone = objXmlReader.Read();
            }
        }
    }

It errors on characters such as é so I guessed this was the fact UTF-8 was specified as the encoding or the way I create the MemoryStream in the above code with ASCIIEncoding. I have tried changing the encoding in both the xsd and xml to UTF-16 and the memorystream to UTF32 but it seems to have no effect. Any ideas?

+1  A: 

Don't convert your input string to ASCII if your input string contains non-ASCII characters.

You can use a StringReader to supply your input string directly to an XmlReader:

using (var reader = XmlReader.Create(new StringReader(xml), settings)) { ...
dtb