1

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>
Baro
  • 5,300
  • 2
  • 17
  • 39
  • dt = new DataTable("table"); dt.ReadXml("data.xml"); – jdweng Aug 25 '22 at 21:01
  • 1
    Are you just looking for [`ds.Tables[0].WriteXml("data.xml".XmlWriteMode.WriteSchema)`](https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable.writexml?view=net-6.0#system-data-datatable-writexml(system-string-system-data-xmlwritemode))? That will include the schema in the XML, so that, when read, the resulting data table will contain the original columns, even if there were no rows. – dbc Aug 26 '22 at 03:55
  • @dbc If you write your comment as an answer I will accept it as the correct answer. Thanks so much. – Baro Aug 26 '22 at 09:02
  • You're welcome. I found what looks to be a duplicate: [Loading a datatable into a xml and xml back into a datatable](https://stackoverflow.com/a/12461911/3744182). I edited the title of that question to make it a better canonical duplicate. – dbc Aug 26 '22 at 15:29

0 Answers0