vborutenko
vborutenko

Reputation: 4443

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

Upvotes: 3

Views: 1716

Answers (2)

Ronak Patel
Ronak Patel

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

Marc Gravell
Marc Gravell

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:

  • 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)

Upvotes: 2

Related Questions