views:

318

answers:

2

I use the StreamReader class to obtain XML for my GeoCoding process from Google.

StreamReader srGeoCode = new StreamReader(WebRequest.Create(Url).GetResponse().GetResponseStream());
String GeoCodeXml = srGeoCode.ReadToEnd();
XmlDocument XmlDoc = new XmlDocument();
GeoCode oGeoCode = new GeoCode();
XmlDoc.Load(GeoCodeXml);

I get XML back but it adds \n and other extras to the XML

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<kml xmlns=\"http://earth.google.com/kml/2.0\"&gt;&lt;Response&gt;\n  <name>

I have the same code in VB and it does not do this. I can successfully GeoCode my information using the VB version of this console app.

Is there a reason the C# version adds this extra data to the XML that I retrieve back? I am trying my best to convert everything over to C#. I enjoy coding in it over VB.

Here is the VB Code:

    Dim wreqGeoCode As WebRequest = WebRequest.Create(strURL)
    Dim wresGeoCode As WebResponse = wreqGeoCode.GetResponse
    Dim srGeoCode As New StreamReader(wresGeoCode.GetResponseStream())
    Dim strXML As String = srGeoCode.ReadToEnd()
    Dim xmlDoc As New XmlDocument
    xmlDoc.LoadXml(strXML)
+1  A: 

y not just do

   GeoCodeXml=GeoCodeXml.Replace("\n","");

if it is truly returning the \n as mentioned here.

ANC_Michael
I can probably do that, was just trying to see why it's doing it.
Terry
+4  A: 

You need XmlDoc.LoadXml if you're going to load a string. Load loads from a file.


BTW, the alternative is also more efficient. You can load the document directly from the stream:

WebRequest webRequest = WebRequest.Create(Url);
using (WebResponse webResponse = webRequest.GetResponse())
{
    using (Stream responseStream = webResponse.GetResponseStream())
    {
        XmlDocument XmlDoc = new XmlDocument();
        GeoCode oGeoCode = new GeoCode();
        XmlDoc.Load(responseStream);
    }
}

The using statements ensure that the WebResponse and Stream get cleaned up, even if an exception is thrown.

John Saunders
+1, Yep, definitely this one, his VB version uses LoadXml and it works. His C# one uses Load and it doesn't.
Kazar
Thank you. I thought I copied that over from the VB one but it looks like I didn't.Always nice to have a second pair of eyes look at your code.
Terry
Thanks! I will look into changing the code to be more efficient. On a side note, we have the same last name - lol
Terry