Bug #696

avatar

Unhandled XmlException on invalid XML

Added by J W 4418 days ago. Updated 4418 days ago.

Status:New Start:02/22/2012
Priority:Normal Due date:
Assigned to:- % Done:

0%

Category:- Spent time: -
Target version:-
Votes: 0

Description

I've got this exception:

System.Xml.XmlException was unhandled
Message=An error occurred while parsing EntityName. Line 1, position 459.
Source=System.Xml
LineNumber=1
LinePosition=459
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseEntityName()
at System.Xml.XmlTextReaderImpl.ParseEntityReference()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.LoadXml(String xml)
at Mono.Nat.Upnp.MessageBase.Decode(UpnpNatDevice device, String message) in C:\Projects\mono-Mono.Nat-e03fd86\Mono.Nat\Upnp\Messages\UpnpMessage.cs:line 78

From this XML response:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetGenericPortMappingEntryResponse xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1"><NewRemoteHost></NewRemoteHost><NewExternalPort>2727</NewExternalPort><NewProtocol>UDP</NewProtocol><NewInternalPort>0</NewInternalPort><NewInternalClient></NewInternalClient><NewEnabled>0</NewEnabled><NewPortMappingDescription>AT&T D-Link DVG-1402M ATA [MICROSOFT]</NewPortMappingDescription><NewLeaseDuration>0</NewLeaseDuration></u:GetGenericPortMappingEntryResponse></s:Body></s:Envelope>

The issue definitely seems to be the unescaped '&' in 'AT&T' there. Not a big surprise that bad XML leads to an exception, but I'll see what I can do about fixing it anyway.

History

Updated by J W 4418 days ago

avatar

Was easy to fix. Added this method to Mono.Nat.Upnp.MessageBase:

private static string SanitizeXml( string message )
{
// Invalid XML will stymie the XmlDocument.Load method, so we'll check for possible problems
StringBuilder sanitized = new StringBuilder( message );
for(int i = 0; i < sanitized.Length; ++i) {
if (sanitized[i] == '&') {
if (sanitized.ToString( i, 5 ) != "&amp;") {
sanitized.Replace( "&", "&amp;", i, 1 );
}
}
} }
return sanitized.ToString();

All references to XmlDocument.LoadXml can be changed like this:

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml( SanitizeXml( message ) );

And thusly, problem solved.

Also available in: Atom PDF