使用XMLRoot/XMLElement和使用Serializable()属性之间的区别(在c#中)

Rod*_*iko 12 c# serialization serializable xmlroot

使用XMLRoot/XMLElement和使用Serializable()属性有什么区别?我怎么知道何时使用?

Chr*_*lor 30

这里有一个不太深入的描述,但我认为这是一个很好的起点.

XmlRootAttribute - 用于为将要作为被序列化的对象图的根元素的类提供模式信息.这只能应用于类,结构,枚举,返回值的接口.

XmlElementAttribute - 为控制如何将它们序列化为子元素的类的属性提供模式信息.此属性只能应用于字段(类变量成员),属性,参数和返回值.

前两个XmlRootAttributeXmlElementAttributeXmlSerializer有关.而下一个,由运行时格式化程序使用,并且在使用XmlSerialization时不适用.

SerializableAtttrible - 用于指示类型可以由运行时格式化程序(如SoapFormatter或BinaryFormatter)序列化.只有在需要使用其中一种格式化程序序列化类型时才需要这样,并且可以应用于委托,枚举,结构和类.

这是一个快速示例,可能有助于澄清上述内容.

// This is the root of the address book data graph
// but we want root written out using camel casing
// so we use XmlRoot to instruct the XmlSerializer
// to use the name 'addressBook' when reading/writing
// the XML data
[XmlRoot("addressBook")]
public class AddressBook
{
  // In this case a contact will represent the owner
  // of the address book. So we deciced to instruct
  // the serializer to write the contact details out
  // as <owner>
  [XmlElement("owner")]
  public Contact Owner;

  // Here we apply XmlElement to an array which will
  // instruct the XmlSerializer to read/write the array
  // items as direct child elements of the addressBook
  // element. Each element will be in the form of 
  // <contact ... />
  [XmlElement("contact")]
  public Contact[] Contacts;
}

public class Contact
{
  // Here we instruct the serializer to treat FirstName
  // as an xml element attribute rather than an element.
  // We also provide an alternate name for the attribute.
  [XmlAttribute("firstName")]
  public string FirstName;

  [XmlAttribute("lastName")]
  public string LastName;

  [XmlElement("tel1")]
  public string PhoneNumber;

  [XmlElement("email")]
  public string EmailAddress;
}
Run Code Online (Sandbox Code Playgroud)

鉴于上述情况,使用XmlSerializer序列化的AddressBook实例将提供以下格式的XML

<addressBook>
  <owner firstName="Chris" lastName="Taylor">
    <tel1>555-321343</tel1>
    <email>chris@guesswhere.com</email>
  </owner>
  <contact firstName="Natasha" lastName="Taylor">
    <tel1>555-321343</tel1>
    <email>natasha@guesswhere.com</email>
  </contact>
  <contact firstName="Gideon" lastName="Becking">
    <tel1>555-123423</tel1>
    <email>gideon@guesswhere.com</email>
  </contact>
</addressBook>
Run Code Online (Sandbox Code Playgroud)

  • @Dhanashree,您是否要求将联系人元素包装在父联系人元素中?如果是,那么您可以从'Contact [] contacts'中删除[XmlElement("contact")],如果您想控制名称,那么您可以用[XmlArray("contacts")],XmlArrayItem("替换当前属性)联系")],它将控制根的名称和集合中的项目. (2认同)