编辑:使用 Jon Skeet 提供的代码。
我收到以下错误:
Message: There is an error in XML document (2, 2).
Inner Exception: {"<Translator xmlns=''> was not expected."}
如果有帮助,我可以提供以下代码:
翻译器.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
}
短语.cs:
public class Phrase
{
public PhraseID PhraseID { set; get; }
public string PhraseString{ set; get; }
public Phrase()
{
}
}
短语ID.cs
[Serializable]
public enum PhraseID
{
none,
Button_Start,
Button_Stop,
}
我这样使用它:
设置:
private Translator _translator;
_translator = new Translator();
保存:
Helpers.XmlSerializerHelper.Serialize(
System.AppDomain.CurrentDomain.BaseDirectory + "\\LanguagePacks\\" + langPackName.Text + ".xml",
_translator);
加载:
_translator = new Translator(); //yes this is needed ;)
_translator.LoadLanguage(preloadedLangCombo.SelectedItem.ToString());
使用上面的代码保存 XML 文件时,它会输出以下内容:
英文.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>