Pass string variable to XmlAttribute XMLSerializer

Let's say I have the following code and you want to serialize to XML under the code:

class Human
{
    [XmlElement("OwnedObjects")]
    public List<WorldObjects> ownedObjects;
}

class WorldObjects
{
    [XmlIgnore]
    public string type;
    [XmlAttribute(type)]
    public string name;

    public WorldObjects(string _type, string _name)
    {
        type = _type;
        name = _name;
    }
}

Human bob = new Human;
bob.ownedObjects = new List<WorldObjects>;
bob.ownedObjects.Add(new WorldObjects(drink, tea));

// Serialize

XML:

<Human>
    <OwnedObjects drink="tea" />
</Human>

The string [XmlAttribute(type)]will result in an error.

Is it possible to change the attribute name by passing a string variable?

Thanks in advance.

EDIT: I have to apologize, I missed such a simple solution. Thanks for the answer. Also, thanks to Ben and dbc for the suggestion for better design.

+4
source share
1 answer

[XmlAnyAttribute] . , (, XmlAttribute) XML. , , :

public class WorldObjects
{
    [XmlAnyAttribute]
    public XmlAttribute [] Attributes
    {
        get
        {
            var attr = new XmlDocument().CreateAttribute(XmlConvert.EncodeLocalName(type));
            attr.Value = name;
            return new[] { attr };
        }
        set
        {
            var attr = (value == null ? null : value.SingleOrDefault());
            if (attr == null)
                name = type = string.Empty;
            else
            {
                type = XmlConvert.DecodeName(attr.Name);
                name = attr.Value;
            }
        }
    }

    [XmlIgnore]
    public string name;

    [XmlIgnore]
    public string type;

    // XmlSerializer required parameterless constructor
    public WorldObjects() : this(string.Empty, string.Empty) { }

    public WorldObjects(string _type, string _name)
    {
        type = _type;
        name = _name;
    }
}

XmlConvert.EncodeLocalName() , type XML. XML , , , .

fiddle.

, type="drink" name="tea", XML , , . [XmlAnyAttribute] xsd:anyAttribute, . , <OwnedObjects>.

+3

Source: https://habr.com/ru/post/1667238/


All Articles