Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal characters in XML document in ASP.NET Web Service

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?

like image 231
Boog Avatar asked Feb 14 '09 22:02

Boog


People also ask

Which characters are illegal in XML elements?

The only illegal characters are & , < and > (as well as " or ' in attributes, depending on which character is used to delimit the attribute value: attr="must use &quot; here, ' is allowed" and attr='must use &apos; here, " is allowed' ). They're escaped using XML entities, in this case you want &amp; for & .

Is an XML character illegal?

Some special characters are not permitted in XML attribute values. Note that the ampersand (&) and less-than (<) characters are not permitted in XML attribute values.

Does XML allow special characters?

The XML functions of the database server automatically handle special characters. When a SQL result set contains special characters, the XML function will automatically handle it. These special characters are listed in the following table.


1 Answers

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!

like image 102
Boog Avatar answered Nov 15 '22 01:11

Boog