Fiddling around with XML responses
My year started with new challenges, first of which is malformed and unformatted XML. One of the requirements of a new project I'm working on is to read a simple XML response from a web service and do something with the data. How hard could it be?
Like any other developer, debugging tools like Fiddler is my friend. After capturing the response, I noticed that the contents were malformed and not properly formatted, but still "valid" XML.
Viewing the actual raw response, I realized that the apparent XML elements within the root 'string' element where actually encoded literal strings:
After accepting that I can't change the world, but definitely change the way you think about it, I decided to create a helping aid in the form of a Fiddler extension to help me make sense of the so-called XML.
Creating a Fiddler Extension
The first thing we have to do is create a new class library project in Visual Studio. We are going to target Fiddler version 4, so make sure the .NET target framework is set to 4.0.
Next, we need to add a reference to our project to the Fiddler assembly located at %programfiles(x86)%\Fiddler2\Fiddler.exe
:
Now we can get coding! Add a new class to the project with the following assembly attribute:
using Fiddler;
[assembly: Fiddler.RequiredVersion("2.3.5.0")]
public class XMLFormatter
{
}
To make this class visible to Fiddler we need to implement the IAutoTamper
interface and in the AutoTamperResponseBefore
function, we can modify the response before it is served to the client.
public void AutoTamperResponseBefore(Session oSession)
{
var value = Encoding.UTF8.GetString(oSession.ResponseBody);
value = value.Replace("<", "<").Replace(">", ">");
oSession.oResponse.headers.Add("Response-Hijacked-By", "Fanie");
oSession.ResponseBody = Encoding.UTF8.GetBytes(value);
}
This will use the provided Session object and replace the XML encoded angle brackets < and > as < and > respectfully. While we at it, I've also decided to brand the response by adding a "Response-Hijacked-By" response header just because we can.
Lastly we need to build the project and copy the DLL to the Fiddler Scripts directory at %programfiles(x86)%\Fiddler2\Scripts\
You may need to restart Fiddler if it was running.
Testing the goodness
Now when we execute the request, the extension kicks in and alters the response as proper XML:
We even got a special signature:
Till next time!