Wednesday, April 15, 2009

Loading XML from a remote URL

I was charged with integrating FedEX freight for a client using soap.

I built the the query string dynamically passing in values such as freight class, weight, Sender zip code, Receiver zip code etc...

The way I normally load XML failed;

XmlTextReader rssReader = new XmlTextReader(fedEx_url);

XmlDocument rssDoc = new XmlDocument();

// Load the XML content into a XmlDocument

rssDoc.Load(rssReader);


I got this error message;

Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 5, position 3.


There are no errors in my code the issue was that the XML produced was invalid. When i viewed the source of the XML file generated I noted that there where four blank lines at the start and two at the end and hence the error generated.

To get round this I had to return the XML to string and then remove trailing and preceding white space;

string clean_xml = cleanXml(fedEx_url);

private string cleanXml(string fedEx_url)
{
Uri url = new Uri(fedEx_url);

string result = "";

// Create the web request
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());

// Read the whole contents and return as a string
result = reader.ReadToEnd();
}

// Remove trailing and preceding white space
Regex regex = new Regex(@">\s*<");

result = regex.Replace(result, "><");

return result.Trim();
}


Once you have your clean XML string you can load it as follows;

XmlReader rssReader = XmlReader.Create(new StringReader(clean_xml));

XmlDocument rssDoc = new XmlDocument();

rssDoc.Load(rssReader);


To get a value from the XML document I did the following;

decimal shipping = Convert.ToDecimal(rssDoc.GetElementsByTagName("net-freight-charges")[0].InnerText.Replace("$", ""));


I was able to solve the above with help form the following postings;
Yahoo Develoepr network
Neil Kilbride's Blog

1 comment:

Chris Wilson said...

Thank you so much for this FedEx post, I am doing the same thing and you saved me countless hours.