LastElb LastElb - 4 months ago 25
Vb.net Question

.NET XMLDocument Encoding issue

I'm facing a quite specific problem at the moment. I'm storing some data in a XMLDocument and saves it on the HDD. They are looking like this:

<?xml version="1.0" encoding="utf-8"?>
<Settings>
<Units>
<Unit>
<Name>Kilogramm</Name>
<ShortName>Kg</ShortName>
</Unit>
<Unit>
<Name>Flasche(n)</Name>
<ShortName>Fl</ShortName>
</Unit>
<Unit>
<Name>Stück</Name>
<ShortName>St</ShortName>
</Unit>
<Unit>
<Name>Beutel</Name>
<ShortName>Btl</ShortName>
</Unit>
<Unit>
<Name>Schale</Name>
<ShortName>Sch</ShortName>
</Unit>
<Unit>
<Name>Kiste</Name>
<ShortName>Ki</ShortName>
</Unit>
<Unit>
<Name>Meter</Name>
<ShortName>m</ShortName>
</Unit>
<Unit>
<Name>Stunde(n)</Name>
<ShortName>h</ShortName>
</Unit>
<Unit>
<Name>Glas</Name>
<ShortName>Gl</ShortName>
</Unit>
<Unit>
<Name>Portion</Name>
<ShortName>Port</ShortName>
</Unit>
<Unit>
<Name>Dose</Name>
<ShortName>Do</ShortName>
</Unit>
<Unit>
<Name>Paket</Name>
<ShortName>Pa</ShortName>
</Unit>
</Units>
</Settings>


I'm Loading the file via XMLDocument.Load() and saveing it with XMLDocument.Save().
But now I saved the file from an old PC and now I got an exception on the special characters (ä,ö,ü), after saving and reloading.

In fact viewing the files in Notepad shows no differences, but viewing on hex there are some! How is this possible?

Answer

You can use this extensionmethod to set the decoding prior to saving.

/// <summary>
/// Gets the XmlDeclaration if it exists, creates a new if not.
/// </summary>
/// <param name="xmlDocument"></param>
/// <returns></returns>
public static XmlDeclaration GetOrCreateXmlDeclaration(this XmlDocument xmlDocument)
{
    XmlDeclaration xmlDeclaration = null;
    if (xmlDocument.HasChildNodes)
        xmlDeclaration = xmlDocument.FirstChild as XmlDeclaration;

    if (xmlDeclaration != null)
        return xmlDeclaration;
    //Create an XML declaration. 
    xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", null, null);

    //Add the new node to the document.
    XmlElement root = xmlDocument.DocumentElement;
    xmlDocument.InsertBefore(xmlDeclaration, root);
    return xmlDeclaration;
}

Usage:

XmlDeclaration xmlDeclaration = xmlDocument.GetOrCreateXmlDeclaration();
xmlDeclaration.Encoding = Encoding.UTF8.WebName;
xmlDocument.Save(@"filename");
Comments