I have a WPF application and am trying to use an XML to save some simple data.
I can read and write without problems, but only if my XML has at least one row (as below). When I start the app I read the XML first and I can create the DataView
but if the XML is empty obviously my DataView
cannot work, does not have a table (new DataView(ds.Tables[0])
).
C# functions
private void ReadDatabase() {
ds = new DataSet();
ds.ReadXml("data.xml");
dg.ItemsSource = new DataView(ds.Tables[0]);
}
private void WriteDatabase() {
ds.Tables[0].WriteXml("data.xml");
}
data.xml
<?xml version="1.0" encoding="utf-8" ?>
<table>
<row>
<key></key>
<action></action>
</row>
</table>
Is it possible to insert the table structure into the XML file ?
Thanks
SOLUTION
Thanks to @dbc which gave me the right direction to solve the problem.
I loaded the above XML into the dataset, once the datagrid has been updated I removed the blank line and saved the XML with no rows but with the parameter XmlWriteMode.WriteSchema
and I got the result I was looking for.
c#
private void WriteDatabase() {
ds.Tables[0].WriteXml("data.xml", XmlWriteMode.WriteSchema);
}
data.xml
I was looking for
<?xml version="1.0" standalone="yes"?>
<table>
<xs:schema id="table" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="table" msdata:IsDataSet="true" msdata:MainDataTable="row" msdata:Locale="en-US">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="row">
<xs:complexType>
<xs:sequence>
<xs:element name="key" type="xs:string" minOccurs="0" />
<xs:element name="action" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
</table>