Generate Objects from Xml Files

Share on facebook
Share on twitter
Share on linkedin
Share on reddit

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

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.

Armand Niculescu

Armand Niculescu

As the Senior Project manager, Armand is one of the rare kind of developers that can do both design and programming with equal skill. This, coupled with a solid background and many years of experience, enables him to see the big picture and plan for the small details.

3 Responses

  1. 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. 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.