views:

376

answers:

1

This is a two part question. The first is a specific question about DataSets and XML. The second is a more general "am I taking the right approach" type question. While I'd certainly appreciate replies that answer both questions, I'd also welcome answers that only tackle one or the other!

Question 1

Does the DataSet class support mixed complex type elements? For example, let's say I have the following XML:

<cars>
   <car id="1">10000
     <colour>blue</colour>
     <doors>4</doors>
   </car>
</cars>

The XSD describing this XML will have a complex type with the "mixed" attribute set to true. This allows me to have the value of my car ($10,000) in plain text, following by whatever other elements I need.

However, when I convert this XML into a DataSet and back again using the following code:

StringReader sr = new StringReader(xml);
DataSet dataset = new DataSet();
dataset.ReadXml(sr);
sr.Close();

StringWriter sw = new StringWriter();
dataset.WriteXml(sw);
xml = sw.ToString();
sw.Close();

Then the resulting XML is as follows:

<cars>
   <car id="1">
     <colour>blue</colour>
    <doors>4</doors>
  </car>
</cars>

i.e. the value "10000" goes missing.

This occurs not only if I have the ReadXml() call infer the XML schema (as above), but also if I provide an XSD (eg by calling ReadXmlSchema()).

Is there any way to avoid this? Or should I just make sure I avoid mixed types?

Question 2

Are there any other limitations, such as the one outlined above, that I should be aware of when converting XML to DataSets and vice versa?

Or perhaps Question 1 indicates that I am going about things in reverse order. At the moment I am starting with the desired XML (such as the cars example above), and am converting this into a DataSet. The intention is to persist the data as XML to a database, and when I wish to display this data on a WinForm, I'll convert the XML to a DataSet and use data binding on the various tables in the DataSet. But rather than starting with an XSD, perhaps I should be defining my data as a (typed) DataSet first, and then let the ReadXml/WriteXml methods take care of what the XML looks like?

A: 

Thank you for all of the replies. ;)

Seeing as no one was able to help, I thought I'd attempt to answer my own question:

Question 1 - mixed type elements are simply not allowed by the DataSet class. The only confirmation I could find on this, other than my own testing, is this MSDN forum post, where the ADO.NET program manager writes, "This behavior is by design - DataSet does not support mixed content XML/XSD."

Question 2 - This demonstrates the danger in starting with the XML/XSD in mind, and trying to convert that into a DataSet. This has led to us re-thinking our approach, with the aim of starting with the DataSet first and letting the XML format be derived from it, rather than the other way around.

(Anyone else's thoughts still welcome!)

Justin