Reputation: 4443
I have some class,fox example
public class Test
{
[XmlElement(IsNullable = true)]
public string SomeProperty{get;set;}
}
When I serialize object of this class,I get
<test>
<SomeProperty>value<someproperty>
<test>
But I need add attribute to SomeProperty without changing structure of class and get this
<test>
<SomeProperty Search="true">value<someproperty>
<test>
How can I do that?
PS:I know,that i can write object that include "SomeProperty" and Bool property "Search",but it will change structure of class
Upvotes: 3
Views: 1716
Reputation: 2610
the following class structure will produce the given xml
[XmlRoot("test")]
public class Test {
[XmlElement("items")]
public MyListWrapper Items {get;set;}
}
public class MyListWrapper {
[XmlAttribute("Search")]
public string Attribute1 {get;set;}
[XmlElement("item")]
public List<MyItem> Items {get;set;}
}
public class MyItem {
[XmlAttribute("id")]
public int Id {get;set;}
}
and the xml would be
<?xml version="1.0" ?>
<test>
<items search="hello">
<item id="1" />
<item id="2" />
<item id="3" />
</items>
</test>
Upvotes: 1
Reputation: 1062590
To do that with XmlSerializer
, you would need to have a second type with an [XmlAttribute]
an [XmlText]
. The only other option is IXmlSerializable
, which is: a lot of work and easy to get wrong.
Options:
SomeProperty
SomeProperty
- and mark SomeProperty
as [XmlIgnore]
IXmlSerializable
(ouch)XmlSerializer
at all (looking at LINQ-to-XML or a DOM, for example)XmlSerializer
, but edit the xml afterwards (for example via a DOM or xslt)Upvotes: 2