Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding xml attribute to property

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

like image 209
vborutenko Avatar asked Sep 10 '26 19:09

vborutenko


1 Answers

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:

  • change the structure of SomeProperty
  • add a shim property in parallel with SomeProperty - and mark SomeProperty as [XmlIgnore]
  • use an entirely separate DTO model for serialization (always my go-to option when serialization doesn't fit cleanly)
  • use IXmlSerializable (ouch)
  • don't use XmlSerializer at all (looking at LINQ-to-XML or a DOM, for example)
  • use XmlSerializer, but edit the xml afterwards (for example via a DOM or xslt)
like image 116
Marc Gravell Avatar answered Sep 13 '26 15:09

Marc Gravell