Martin Spedding's Blog

Adventures in a disconnected world

Datasets and encoding...how do I do it ?

I am writing an application that stores information in a dataset and then serializes it to an xml file. Every month the serialized data is emailed to a Exchange public folder. In some ways it is an asynchronous xml web services. I am working in Switzerland which means people use umlauts where writing e.g. ä or ü or ö. Everything works well on the local machine because the serialized xml file is stored as unicode. However, the encoding is not specified in the xml declaration as it should i.e.

<?xml version="1.0" standalone="yes"?>

is used and not

<?xml version="1.0" encoding="UTF-16" ?>

Which is a pain later on as I am inserting the serialized data into the body of mail message rather than attaching it.  Whether that is the sensible approach is another question but I am surprised that as a default that datasets are not saved with the correct encoding set.

The question is how do serialize the dataset so that it specifies the encoding ?

Comments

Don Box said:

If you use the DataSet.WriteXml method that takes either a TextWriter or XmlWriter, you'll have already set that up by the time you call WriteXml. FWIW, the constructor to XmlTextWriter accepts a System.Text.Encoding to indicate which encoding you want to use.

The code you want should look something like this:

XmlWriter writer = new XmlTextWriter("file.xml", Encoding.Unicode);
dataSet.WriteTo(writer);
writer.Close();



# April 14, 2003 2:32 PM

Augusto Cosatti said:

Hello.

I used this piece of code to write out a dataset to a XML stream with default encoding. I'm using a MemoryStream instead of a TextWriter.

MemoryStream memStream = new MemoryStream();

StreamWriter writer = new StreamWriter(memStream, Encoding.Default);

           ds.WriteXml(writer, XmlWriteMode.WriteSchema);

// Return XML string

return Encoding.Default.GetString(memStream.GetBuffer());

Regards

Augusto

# July 30, 2008 10:55 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)