views:

30

answers:

1

I am trying to come up with a windows form application (or WPF) developed in C#.The requirement for my app is to get user search related xml node data from a website containing xml. The application would connect to a website containing xml and grab relevant xml nodes from the website. I would then display the xml node data on my windows app. What's the best way to do this, also an extension would be to grab all the xml and store in a data tier. An sample website I will be similar to this page http://www.amk.ca/quotations/sherlock-holmes.xml

+2  A: 

Not entirely sure what your questions is - are you asking how to achieve this (downloading XML), or where to best put it, or what?

To grab the XML, use something like this:

using System.Net;

WebClient client = new WebClient();
string result = client.DownloadString("http://www.amk.ca/quotations/sherlock-holmes.xml");

You get back a string of XML, which you can now parse using XmlDocument or XDocument (Linq-to-XML) - are you asking how to do this??

Or if you know what sites and what format XML you're hitting ahead of time, you could also download the XML and generate a XML schema from it, and in a second step generate C# classes from the XML schema that would be suitable for deserializing the XML string into an enumeration of e.g. Quotation classes (based on the <quotation> tag in the sample XML provided).

Update: if you have a sample XML as a file, you can use the xsd.exe command line utility to generate a XML schema from the XML, and based on that XML schema, you can create a C# class to be used for deserialization. See the MSDN docs for xsd.exe for more details.

Basically, calling xsd.exe (yourfile.xml) will generate a yourfile.xsd XML schema based on your XML input file, and running xsd.exe /c (yourfile.xsd) will generate a C# class from that XML schema.

Using that, you could deserialize your XML into a C# class in one step and then "explore" the contents of the XML by just navigating around the C# class, its properties, and its lists of subelements.

That deserialization would look something like this:

XmlSerializer deserializer = new XmlSerializer(typeof(ThatDataTypeGenerated));

object result = deserializer.Deserialize(<either a file name, or a stream or something>);

This works as long as you know ahead of time what XML type you'll be getting (so that you can generate the XML schema and C# class from it, ahead of time).

Also, you can do the first step (turn XML data file into schema) inside Visual Studio, too (menu "XML" -> "Generate XML schema"), and for the second step (turning the XSD XML schema into a C# class), you could have a look at something like Xsd2Code.

marc_s
Thank you, you solved my problem. I know now how to grab the XML and then I can parse it like you said using Quotation classes. Also, if you could elaborate a bit on doing the classes, that would be great
Sam
@Sam: elaborated...
marc_s