EDIT: Using the code provided by Jon Skeet.
I get the following error:
Message: There is an error in XML document (2, 2).
Inner Exception: {"<Translator xmlns=''> was not expected."}
If it helps I can provide the code below:
Translator.cs:
public class Translator
{
public FullBotTranslation Translation;
public Translator()
{
Translation = new FullBotTranslation();
}
public void LoadLanguage(string language)
{
if (!Useful.ExistFile(System.AppDomain.CurrentDomain.BaseDirectory + "\\LanguagePacks\\" + language + ".xml"))
language = "Francais";
Translation = XmlSerializerHelper.Deserialize<FullBotTranslation>(System.AppDomain.CurrentDomain.BaseDirectory + "\\LanguagePacks\\" + language + ".xml");
}
public string GetTranslation(PhraseID phraseId)
{
foreach (Phrase phrase in Translation.Phrases)
{
if (phrase.PhraseID == phraseId)
return phrase.PhraseString;
}
return "Incomplete translation...";
}
#region Nested type: Translation
[Serializable]
public class FullBotTranslation
{
public List<Phrase> Phrases = new List<Phrase>();
}
#endregion
}
Phrase.cs:
public class Phrase
{
public PhraseID PhraseID { set; get; }
public string PhraseString{ set; get; }
public Phrase()
{
}
}
PhraseID.cs
[Serializable]
public enum PhraseID
{
none,
Button_Start,
Button_Stop,
}
I use it like this:
Setup:
private Translator _translator;
_translator = new Translator();
Saving:
Helpers.XmlSerializerHelper.Serialize(
System.AppDomain.CurrentDomain.BaseDirectory + "\\LanguagePacks\\" + langPackName.Text + ".xml",
_translator);
Loading:
_translator = new Translator(); //yes this is needed ;)
_translator.LoadLanguage(preloadedLangCombo.SelectedItem.ToString());
When using the code above to save an XML file it outputs the following:
English.XML:
<?xml version="1.0"?>
<Translator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Translation>
<Phrases>
<Phrase>
<PhraseID>none</PhraseID>
<PhraseString>Incomplete Translation</PhraseString>
</Phrase>
<Phrase>
<PhraseID>Button_Start</PhraseID>
<PhraseString>Start</PhraseString>
</Phrase>
<Phrase>
<PhraseID>Button_Stop</PhraseID>
<PhraseString>Stop</PhraseString>
</Phrase>
</Phrases>
</Translation>
</Translator>
It’s not clear what’s going wrong here – particularly because the error message doesn’t seem to match your sample XML. Your exception handling may well be hiding problems though – it’s a really bad idea to catch all exceptions like that, and you’re going to unnecessary lengths to close the streams involved. I would condense your class down to just this:
Now if something goes wrong, the exception will propagate out of the methods, rather than being disguised. Also, note that I’ve serialized to/from just streams, rather than getting a
StreamWriterinvolved. It’s simpler to let the XML infrastructure deal with all the encoding.The above code works fine for me in a simple test.