Recently needed some quick method to use objects generated from an existing xml file without bothering to create an xml schema for it.
After a few attempts and searching for explanations why a simple task like this wouldn´t work, finally put the steps together:
1. Use VS2008 CommandPrompt Tool and run :
xsd.exe xmlNameFile.xml /outputdir:DirName
2. The above will generate xsd schema in the directory (.xsd file)
3. Use xsd tool again in the VS CommandPrompt to generate the classes from the new schema :
xsd.exe NewSchemaName.xsd /c /n:YourNamespace
This will generate a class file that you can use in your project but be aware of the following :
For parent elements in xml it will automatically generate a field as a multidimensional array , i.e.
Items with the
XmlArrayItemAttribute("TagName", typeof(Items) but as
Items is multidimensional it won’t cope with it, even if one changes the type to
typeof(Items) these are filled with null.
4. You need to change the whole into a one dimensional array :
private Items itemsField;
This will fill the array with all the nodes that are under TagName automatically.
5. Then you can use a Deserialization method to get the whole object , like :
public object DeSerializeObject(string s, Type t)
Stream xmlStream = new MemoryStream(s.Length);
StreamWriter sw = new StreamWriter(xmlStream);
XmlSerializer serializer = new XmlSerializer(t);
And method usage :
Response rsp = (Response)this.DeSerializeObject(doc.InnerXml, typeof(Response))
The result is an object having the structure of the xml file provided at the beginning.