I am trying to deserialize a Value as either a XmlAttribute or a XmlText for equal xml tags.
When deserializing, both options should be valid and both options should end up deserializing a value into the same Property of a class.
Basically my xml looks like this:
<ArrayTest>
<ArrayItem>Item1</ArrayItem>
<ArrayItem Value="Item2"/>
</ArrayTest>
And given the classes:
public class ArrayTest
{
[XmlElement(nameof(ArrayItem))]
public ArrayItem[] Items { get; set; }
}
public class ArrayItem
{
//[XmlAttribute]
//[XmlText]
public string Value { get; set; }
}
I want "Item1" as well as "Item2" to end up in the Value property of the respective ArrayItems.
I know something like this is done in xaml for WPF, for instance when defining the Text Property of a TextBlock i am able to set it either within the xml tags as well as directly within the Text Property. I.e.
<TextBlock Text="Sample text"/>
<TextBlock>
Sample Text
<TextBlock/>
I already tried different combinations of the corresponding class attributes, but it seems that the last one just ends up overwriting the previous one so i'm just left with one of both options.
Additionally i would prefer if this was possible using the XmlSerializer Class.
Edit: Inspired by Auditive's answer I went with this:
public class ArrayItem
{
[XmlAttribute(nameof(Value))]
public string ValueAttribute
{
get => mValue;
set => mValue = value;
}
[XmlText]
public string Value
{
get => mValue;
set => mValue = value;
}
private string mValue;
}
This works for my case.
Do note however, that this won't work for serialization, as that way both properties get saved.
