xml序列化将xmlelement和xmlattribute一起指定

时间:2010-09-29 16:10:28

标签: c# .net xml-serialization

鉴于: -

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

   [XmlElement]
   public string Publisher;

   [XmlElement]
   public string PublisherReference;
}

序列化为XML时会给出

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

如何将PublisherReference作为Publisher的属性 - 例如

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

1 个答案:

答案 0 :(得分:16)

[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;
}