多语言程序与xml

时间:2012-05-18 12:35:06

标签: xml parsing multilingual

我想在我的程序中实现多种语言。我正在使用像这样的xml文件:

    <?xml version="1.0" encoding="utf-8"?>
<root> 
 <language id="EN">
 <String id="rxtst_found">.rxtst found</String>
 <String id="exe_found">.exe found</String>
 <String id="rxtst_not_found">No .rxtst found</String>
 <String id="exe_not_found">No .exe Found</String>
 </language>
 <language id="DE">
    <String id="exe_found">.exe gefunden</String>
    <String id="rxtst_found">.rxtst gefunden</String>
    <String id="rxtst_not_found">Keine .rxtst gefunden</String>
    <String id="exe_not_found">Keine .exe gefunden</String>
 </language>
     </root>

我想这样称呼语言:

getStringValue(String string_id, language lang) ...

什么是正确解析语言的最佳方法? 我想过像

这样的东西
           XmlNodeList xmlNodesByLanguage = xdoc.GetElementsByTagName("language");
...
           String tempLang =  xmlNodesByLanguage.Item(i).Attributes["id"].Value;

但我不知道......

2 个答案:

答案 0 :(得分:0)

您可以改为使用SelectSingleNode方法,并为要查询的节点提供有效的XPath。

以下示例效果很好。不过它在VB.NET中

Dim string_id As String = "rxtst_found"
Dim language As String = "DE"

Dim xdoc As XmlDocument = New XmlDocument
xdoc.Load("C:\\sample.xml")

Dim xPath = "root/language[@id='" + language + "']/String[@id='" + string_id + "']"
Dim languageNode = xdoc.SelectSingleNode(xPath)
Dim result = languageNode.InnerText

答案 1 :(得分:0)

我使用xsd.exe反序列化了我的xml,并使用以下代码读取数据:

            //deserializes language xml

            XmlSerializer ser = new XmlSerializer(typeof(root));
            String asdf = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

 FileStream fs = new FileStream(asdf + "\\XML\\language.xml", FileMode.Open);

                XmlReader reader = new XmlTextReader(fs);
                //root = head node of the xml file

 root ts = (root)ser.Deserialize(reader);
            fs.Close();
            //sprachennummer nach enum in Siro_Settings
            int languageNr = (int)lang;

            //sucht nach dem passenden Value zu der stringID und gibt ihn zurück
            for (int j = 0; j < ts.Items[languageNr].String.Length; j++)
            {
                if (ts.Items[languageNr].String[j].id.Equals(stringID))
                {
                    return ts.Items[languageNr].String[j].Value;
                }

            }