Tuesday, April 7, 2015

DataTable does not support schema inference from Xml error ?


If you are reading xml to Datatable using the method like below, it will throw a error.
string xmlString ="somexml string"; /// this will actually contain the xml...
DataTable dt = new DataTable();
System.IO.StringReader oreader=new System.IO.StringReader (xmlString);
dt.ReadXml(oreader);

this might throw a error like DataTable does not support schema inference from Xml error.

This happens because the Datatable doesnt understand the Schema to properly convert to a DataTable.

Two way to solve this.
1) Easier way is to use the Dataset and then get the table from there like below

string xmlString ="somexml string"; /// this will actually contain the xml...
DataSet ds = new DataSet();
System.IO.StringReader oreader=new System.IO.StringReader (xmlString);
ds.ReadXml(oreader);
DataTable dtt=ds.tables[0];

2) If the XmlString has the Schema use the following

string xmlString ="somexml string"; /// this will actually contain the xml...
DataTable dt = new DataTable();
System.IO.StringReader oreader=new System.IO.StringReader (xmlString);
dt.ReadXmlSchema("xmlSchema.xsd"); -- If schema is in a xsd
dt.ReadXmlSchema(oreader); // if the XML string has the XML Schema.
dt.ReadXml(oreader);


Note: If you are generating the XML as well from a datatable you can generate the schema by
dt.WriteXml("a.xml",XmlWriteMode.WriteSchema);
  If you are not generating the XML, you can still generate schema from different XML editors. Like for EX if you have visual Studio you can use the create Schema to create the XML and then load it or the easier way of using the Dataset :)

Cheers,
Bob






             

No comments:

Post a Comment