Friday, April 22, 2011

XSD to XML in c#

private void ReadSchemaFromXmlTextReader(string filename){
// Create the DataSet to read the schema into.
DataSet thisDataSet = new DataSet();
// Create a FileStream object with the file path and name.
System.IO.FileStream myFileStream = new System.IO.FileStream
(filename,System.IO.FileMode.Open);
// Create a new XmlTextReader object with the FileStream.
System.Xml.XmlTextReader myXmlTextReader=
new System.Xml.XmlTextReader(myFileStream);
// Read the schema into the DataSet and close the reader.
thisDataSet.ReadXmlSchema(myXmlTextReader);
myXmlTextReader.Close();
}


private void WriteXmlToFile(DataSet thisDataSet) {
if (thisDataSet == null) { return; }
// Create a file name to write to.
string filename = "myXmlDoc.xml";
// Create the FileStream to write with.
System.IO.FileStream myFileStream = new System.IO.FileStream
(filename, System.IO.FileMode.Create);
// Create an XmlTextWriter with the fileStream.
System.Xml.XmlTextWriter myXmlWriter =
new System.Xml.XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);
// Write to the file with the WriteXml method.
thisDataSet.WriteXml(myXmlWriter);
myXmlWriter.Close();
}


First call the ReadSchemaFromXmlTextReader and pass in the xsd string filename. Once the dataset has schema loaded, you can update the dataset with records from the database using maybe a SqlDataAdapter. Once that is done call the WriteXmlToFile and pass in the dataset. Hope this helped.

No comments:

Post a Comment