0

我正在处理一个支持不同语言的 XML 文件,我想使用 XDocument/XElement(使用 System.Xml.Serialization)将此 XML 解析为 C# 类。XML 有点复杂,但我想要实现的应该很简单,但我无法弄清楚。

Basix XML 示例:

<root>
    <word_EN>Hello</word_EN>
    <word_DE>Hallo</word_DE>
    <word_FR>Bonjour</word_FR>
<root>

我希望我的解析器看起来如何:

[XmlRoot("root")]
public class Root
{
    [XmlElement("word_" + LanguageSetting.SUFFIX)]
    public string word { get; set; }
}

我想从另一个类中获取后缀,并且希望能够更改它。我可以将后缀设置为 const 字符串,但我无法更改它。使用全局变量也不起作用。

static class LanguageSetting
{
    private static string _suffix = "EN";
    public static string SUFFIX
    {
        get { return _suffix; }
        set { _suffix = value; }
    }
}

错误: 属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式

添加后缀的正确方法是什么?

4

1 回答 1

1

The correct way of doing this would be for your language suffix to be an XML attribute on the word element but this may not be possible for you.

You are receiving this error because a compile time constant must be use in attribute decorations. LanguageSetting.Suffix is static, but not a constant. Try using the const keyword instead.

In XML, different tag names represent different object types. The best solution for your current XML document is you have seperate classes for each supported language, all inherited from a common class (eg. WordBase).

于 2013-10-29T08:18:01.623 回答