I have an XSD and I have to generate an XML document to send to the customers of the company I work with. The documents I send will be validated against this XSD schema.
What is the best way to create a XML document conforming to a XSD Schema? I mean, I’m searching for best practices and the like. I’m new to this and while “Googling” around here and there, I found people using XmlTextWriter, DataSet.WriteXml, and others.
-
DataSet.WriteXml seems to not work well for me. This is what I did:
var ds = new DataSet(); ds.ReadXmlSchema(schemaFile); ds.Tables["TableName"].Rows.Add("", "", 78, true, DateTime.Now); ... ds.WriteXml("C:\\xml.xml");I found it generates a node with NewDataSet, and the nodes are not in the proper order.
-
XmlTextWriter, I find it a bit long to do… but I will if there is no other choice.
What do you think is the best way to do this? Are there other approaches to do it?
I would put the schema here if it wasn’t so long, and if it were relevant to the question.
The mainstream practice in .NET is to use XML Serialization.
In your case, I would do this:
Example:
Given this schema:
xsd.exe generates this source code:
In your app you can instantiate a Foo and then serialize, like this:
This example serializes into a string. Of course you can serialize to other XmlWriters, you can write out to a file, to any arbitrary stream, and so on.
Normally I tweak the serialization to omit the XML declaration, omit the default xml namespaces, and so on. Like this:
You can also do the reverse – map from an XML document to an in-memory object graph – using the XmlSerializer. Use the Deserialize method.