.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Friday, December 16, 2005

Creating DataSet from XML and XSD

Level: Beginner-Intermediate

If you want to read your XML file into a DataSet, you could use the ReadXml method of the DataSet. You can read the XSD for the same XML file using ReadXMLSchema method. Here is how to use these methods,


string doc = @"c:\test.xml";
string docSchema = @"c:\test.xsd";
XmlDataDocument myXmlDataDocument = new XmlDataDocument ;


We will use a StreamReader to read the schema file,

StreamReader reader = new StreamReader(docSchema);
//this will read the schema to DataSet
myXmlDataDocument.DataSet.ReadXmlSchema(reader);


[do not forget to close the StreammReader in your actual code]

//this will read the XML
myXmlDataDocument.Load(document);


DataSet also has a ReadXML method you can use to read the XML. This method can be used instead of XMLDataDocument's Load method. ReadXML method takes a second parameter that specifies XMLReadMode [enumeration].
Read more about this on MSDN:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatasetclassreadxmltopic.asp

All these methods works well with simple XML and XSD. In my experience, if you have many complex types and relations in XML/XSD, ReadXMLSchema method gives undefined error! on some types [native and sometimes derived!] and subsequently Load fails!!

0 comments: