Link to home
Start Free TrialLog in
Avatar of dban00b
dban00b

asked on

C# XML Parsing from an Internet URL

I've gone around in circles on this one.  Hopefully someone can give me a simple Hello World code.

I want to open an XML file via the internet via something like this
(HttpWebRequest) WebRequest.Create("www.example.com/helloworld.xml");

and parse the file and output the contents.  It doesn't need to be fancy I just hope it ends up with something like this, or I've been WAY off base:

XmlNodeList greeting = myXmlFile.GetElementsByTagName("greeting");
XmlNodeList target = myXmlFile.GetElementsByTagName("target");
Console.WriteLine("{0} {1}",greeting[0].InnerText, target[0].InnerText);



Thanks for your help!
<?xml version="1.0"?>
<root>
	<greeting>Hello</greeting>
	<target>World</target>
</root>

Open in new window

Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

What output do you want to see?

Do you need help downloading a file?
Do you need help parsing the xml string?
Avatar of dban00b
dban00b

ASKER

I'm having trouble changing a HttpWebResponse into an XmlDocument.

Attached is the code I think should work, but doesn't.

The output I'm expecting is "Hello World"
class XmlTest
{
	static void Main(string[] args)
	{
		XmlDocument myXmlFile = new XmlDocument(); 
		HttpWebRequest  myRequest  = (HttpWebRequest) WebRequest.Create("http://www.example.com/helloworld.xml");
 
		myXmlFile.Load((HttpWebResponse) myRequest.GetResponse());
 
		XmlNodeList greeting = myXmlFile.GetElementsByTagName("greeting");
		XmlNodeList target = myXmlFile.GetElementsByTagName("target");
 
		Console.WriteLine("{0} {1}",greeting[0].InnerText, target[0].InnerText);
	}
}

Open in new window

what is the result of the myXmlFile.OuterXml after myXmlFile.Load((HttpWebResponse) myRequest.GetResponse()); line

if you can see your Xml in that then i will change try using following code for printing

XmlNode greeting = myXmlFile.SelectNode("//root/greeting");
XmlNode target = myXmlFile.SelectNode("//root/target");

Console.WriteLine("{0} {1}", greeting.InnerText, target.InnerText);
No ragi0017, I believe the problem is in the response value. The dban00b's xml processing procedure is not much different from yours and is 100% correct.

dban00b, to be sure try to set breakpoints and check what xml are you getting.
I have a feeling that this ((HttpWebResponse) myRequest.GetResponse()).toString() returns something that is not expected...
ASKER CERTIFIED SOLUTION
Avatar of Tony McCreath
Tony McCreath
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dban00b

ASKER

Viola! That was it, I needed to turn the response into a Stream before XmlDocument::Load could read it.

Thanks!