Question

I'm dealing with a XML file which has support for different languages, I want to parse this XML into C# classes using XDocument/XElement (using System.Xml.Serialization). The XML is slightly complex but what I want to achieve should be simple, yet I can't figure it out.

Basix XML example:

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

How I want my parser to look like:

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

I want to get the suffix from another class and I want to be able to change it. I can set the suffix as a const string but then I can't change it. Using a global variable also does not work.

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

Error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

What is the proper way of adding the suffix?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top