Ryan
Ryan

Reputation: 24422

xml serialization specify xmlelement and xmlattribute together

Given :-

[XmlRoot("Book")]
public class Book
{
   [XmlAttribute]
   public string Title;

   [XmlElement]
   public string Publisher;

   [XmlElement]
   public string PublisherReference;
}

When serialized to XML will give

<Book Title="My Book">
   <Publisher>Some Publisher</Publisher>
   <PublisherReference>XYZ123</PublisherReference>
</Book>

How could I get PublisherReference as an attribute of Publisher - e.g.

<Book Title="My Book">
   <Publisher Reference="XYZ123">Some Publisher</Publisher>
</Book>

Upvotes: 13

Views: 15355

Answers (1)

Adrian Zanescu
Adrian Zanescu

Reputation: 8008

[XmlRoot("Book")]
public class Book
{
   [XmlAttribute]
   public string Title;

   [XmlElement]
   public Publisher Publisher;
}

[Serializable]
public class Publisher
{
  [XmlText]
  public string Value;

  [XmlAttribute]
  public string Reference;
}

Upvotes: 18

Related Questions