Generate Objects from Xml Files

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;

and

XmlArrayItemAttribute("TagName", typeof(Items)

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 :

1
2
3
4
5
6
7
8
9
10
public object DeSerializeObject(string s, Type t)
{
    Stream xmlStream = new MemoryStream(s.Length);
    StreamWriter sw = new StreamWriter(xmlStream);
    sw.Write(s);
    sw.Flush();
    xmlStream.Seek(0, SeekOrigin.Begin);
    XmlSerializer serializer = new XmlSerializer(t);
    return serializer.Deserialize(xmlStream);
}

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.

3 replies
  1. iPhone
    iPhone says:

    Thanks for the wonderful post..Almost all the posts on your blog are good but this is one of the best..keep up the good work and sharing your knowledge with others

  2. Xbox 360
    Xbox 360 says:

    Do you know how much time this would have saved me? I’ve been spending ages creating an XML schema for every object I wanted to create! For once someone who posts genuinely useful stuff. Thanks so much,

Comments are closed.