I have an xml file
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfLocations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Location xsi:type="JointLocation">
<Name>Example Location</Name>
<Index>0</Index>
<ZClearance>0</ZClearance>
<Joint1>100</Joint1>
<Joint2>200</Joint2>
<Joint3>200</Joint3>
<Joint4>200</Joint4>
<Joint5>200</Joint5>
<joint6>0</joint6>
<Joint6>0</Joint6>
</Location>
</ArrayOfLocations>
I load this file into a data set, and then into a DataGridView. From that DataGridView I can add new Location elements, or edit existing Location elements and save. When I save, I am doing this
string path = filePathBox.Text;
DataSet ds = (DataSet)dataGridView1.DataSource;
ds.WriteXml(filePathBox.Text);
After saving, the XML file then looks like
<?xml version="1.0" standalone="yes"?>
<ArrayOfLocations>
<Location>
<Name>Example Location</Name>
<Index>0</Index>
<ZClearance>0</ZClearance>
<Joint1>100</Joint1>
<Joint2>200</Joint2>
<Joint3>200</Joint3>
<Joint4>200</Joint4>
<Joint5>200</Joint5>
<joint6>0</joint6>
<Joint6>0</Joint6>
</Location>
</ArrayOfLocations>
As you can see the xsi and namespace have been removed. I would like to preserve these attributes.
So far I have tried adding as an additional parameter to WriteXML():
ds.WriteXML(filepath, XmlWriteMode.WriteSchema)
However, this creates a big mess and still does not maintain the initial format that I want to preserve. Any tips?
A simple example shows us that
ReadXML/WriteXMLwill lose the schema info you're interested inGives us
The best way I found to recover this schema information is to
Deserializethe data. It's not pretty but it worked for me:And of course you'll need to create the classes that model your schema in order to deserialize:
Note the following gotchas
JoinLocationclass, specify that type underXmlInclude, and manually fix your object all in order to comply with the schema that you want to output to.XmlTextWritterto respect indentationThis all should give you the desired output: