khteh
khteh

Reputation: 3996

C# 10 (De)Serialize XML property value AND attributes using StringWriter, StringReader and XmlSerializer

How do I (de)serialize the following xml element:

<OtherInfo name=\"Some Name\" type=\"text\">Hello World!!!\n</OtherInfo>

I define the following class to take care of the attributes:

[Serializable]
public class OtherInfo
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "type")]
    public string Type { get; set; }
    public OtherInfo() { }
    public OtherInfo(string name, string type) => (Name, Type) = (name, type);
}

But how do I handle the property value?

Upvotes: 0

Views: 99

Answers (1)

Maik Hasler
Maik Hasler

Reputation: 1400

Simply add a new property to your class and decorate it with the XmlText attribute. Here a quick link to the documentation.

[Serializable]
public class OtherInfo
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "type")]
    public string Type { get; set; }

    [XmlText]
    public string Value { get; set; }

    public OtherInfo() { }

    public OtherInfo(string name, string type, string value) => (Name, Type, Value) = (name, type, value);
}

Upvotes: 0

Related Questions