5

I'm going to ask and answer my own question, I hope nobody minds but I thought this might be useful to other people.

If you setup a ASP.NET Web Service that returns objects that contain characters that are invalid for XML an exception will be thrown after the object is serialized in to SOAP xml and the client attempts to deserialize that xml.

How do you fix this?

4
  • If your web service is returning poorly-formed XML, the solution is to fix the web service, not patch over the poorly-formed XML. The web service is probably doing other wrong things that you won't be able to hide so easily. Commented Feb 16, 2009 at 10:25
  • It's the data I'm pulling from a db. The characters are encoded correctly, they just aren't valid for xml. I'd rather have my users fix the characters than have my webservice break everytime they input illegal characters. De/Serialization works if you tell the reader to not validate what it reads. Commented Feb 16, 2009 at 18:56
  • What XML component are you using to construct this XML containing invalid characters? I'm going to go out on a limb here and guess the answer is "I'm using string concatenation." Commented Feb 16, 2009 at 19:47
  • No, I'm using XmlSerializer. The data that I'm serializing has odd unprintable characters in it, although XmlSerializer html encodes them, it still throws the exception. I'm using a standard ASP.NET webservice, I didn't make the soap implementation myself. Commented Feb 17, 2009 at 16:41

1 Answer 1

8

To fix this I generated the class file for my webservice with the wsdl.exe application that is part of .NET. This is straight forward to do, at a command prompt just type wsdl.exe <path to webservice>

After that is generated I overloaded the method

protected XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize)

like this

protected override XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.CheckCharacters = false;
    return XmlTextReader.Create(message.Stream, settings);
}

This tells the XmlTextReader to ignore the validity of the XML file it is reading. There's no reason that I care if the xml is valid or not when I'm just going to immediately deserialize it.

Hope this helps someone with the same problem out there!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.