How to load DataTable into XMLDocument?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
B

Brett Romero

I have a DataTable with one column. How can I load that into an
XMLDocument object? XMLDocument.Load() or LoadXML() will not take a
DataTable.

Thanks,
Brett
 
Check out the XmlTextReader and XmlTextWriter classes.
All the samples you need are in MSDN documentation.

1 possible approach is:

Add your data table to a dataset.
Write your dataset to a XML string
Use the XmlDocument's LoadXML method.

Steven Nagy
 
The write your data to XML part is where I'm having trouble. All the
MSDN documentation shows how to writer to a file. That's fine but I'm
not writing to a file. I need the DataSet XML to finally end up in a
string. XmlWriter and TextWriter are both abstract classes.

Thanks,
Brett
 
Yes those 2 are abstract, but thats not the classes I mentioned to
begin with.
What do you get if you cross an 'XmlWriter' and a 'TextWriter'?
An 'XmlTextWriter' !


StringWriter sw = new StringWriter();
XmlTextWriter xtr = new XmlTextWriter(sw);
DataSet ds = new DataSet("Test");
ds.WriteXml(xtr, XmlWriteMode.WriteSchema);
string xml = sw.ToString();


I think this code is right. if not, its close to right.
I'm kind of in CE.NET mode at the moment.

Steven Nagy
 
Thanks. That got it but it's only writing the DataSet name. I'm using
IgnoreSchema at the moment since I don't need it. Here's the code:

DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("myid");
ds.Tables.Add(dt);

System.IO.StringWriter sw = new System.IO.StringWriter();
XmlTextWriter xmltw = new XmlTextWriter(sw);

XmlDocument xmlDoc = new XmlDocument();
ds.WriteXml(xmltw, XmlWriteMode.IgnoreSchema);
string xml = sw.ToString();

I want it to write this:
<myid>1</myid><myid>2</myid>...

Is that possible?

Thanks,
Brett
 
Well not quite. The XML it writes will be something like this:

<MyDataSet>
<MyTable>
<MyID>1</MyID>
</MyTable>
<MyTable>
<MyID>2</MyID>
</MyTable>
</MyDataSet>

You obviously haven't added any data in the above code, so all it will
write is the data set name... because its empty!
If you need the XML written a specific way, you'll have to do it
manually. And also, this means that a dataset can't be constructed
again by reading in that custom XML.

You can also use the XML schema tool that comes as a part of the
Dataset. When you add a new item to your project, an option is the
dataset. You can then construct your schema in a more manual way either
diagramtically or in XML. I'm sure this tool has a proper name and can
be called from windows directly, I just don't know what it is.

Hope this rambling has been at least partially useful.

Steven Nagy
 
Back
Top