I’m using an XmlSerializer. My class:
[Serializable]
[XmlRoot(ElementName="MyClass")]
public class MyClass
{
public string Value;
}
I would like to serialize it so that Value ends up as an attribute of a subelement named (for instance) “Text”.
Desired outcome:
<MyClass>
<Text Value="3"/>
</MyClass>
But NOT (which would be the effect of marking Value as an XmlAttribute)
<MyClass Value="3">
</MyClass>
And NOT (which would be the effect of marking Value as an XmlElement):
<MyClass>
<Value>3</Value>
</MyClass>
How do I achieve this?
I am aware that I could change the type of Value from string to another serializable custom class.
Unfortunately, I have plenty of such properties, so I’d need to create dozens of tiny classes.
Is there any quicker solution?
EDIT:
In response to your comments:
-
No, not every property has to be serialized to a subelement named “Text”. Subelement’s name is unique and unambiguous.
-
Sample output XML:
<visibility> <site visible="yes"/> <comparator visible="no"/> <expiration days="7"/> <comment>blahblahblah</comment> <visibility> -
Sample class:
!
[XmlRoot(ElementName="Visibility")]
public class Visibility
{
[XPath("/site@visible")] // if only this was possible!
public string OnSite
{
get { return SiteVisible ? "yes" : "no"; }
}
[XPath("/comparator@visible")] // as above...
public string InComparator
{
get { return ComparatorVisible ? "yes" : "no"; }
}
[XmlIgnore]
public bool SiteVisible;
[XmlIgnore]
public bool ComparatorVisible;
[XPath("/expiration@days")] // as above...
public int ExpiresAfterDays;
[XmlElement("comment")] // this is easy
public string Comment;
}
Without changing the type of
ValueI think it’s not possible. You can add the attributeXmlElement(ElementName="Text")onValuebut you will obtain a result similar to this:Edited:
Another solution can involve XSLT transformation: you can generate the xml using .Net serialization and after apply a xml transformation.
The trasformation of my example should be something like this: