The use of C # XML serialization and deserialization attributes

Source: Internet
Author: User

The following is the class entity that will be serialized:

[XmlRoot ("Root")]
public class Entity
{
[XmlAttribute (AttributeName = "Attr1")]
public string Attribute1;

[XmlElement ("Secondlevel")]
Public Secondlevel Secondlevel;

public override string ToString ()
{
Return Serializer.serialize (this);
}
}

public class Secondlevel
{
[XmlElement ("Thirdlevel")]
Public list<thirdlevel> Thirdlevel;
}

public class Thirdlevel
{
[XmlAttribute (AttributeName = "Attribute1")]
public string Attribute1;

[XmlAttribute (AttributeName = "Attribute2")]
public string Attribute2;

[XmlElement ("Ele1")]
Public Element Ele1;
}

public class Element
{
[XmlAttribute (AttributeName = "Attr1")]
public string Attribute1;

[XmlText]
public string Value;
}

The following is an example of the serialized XML file for an entity class:

<?xml version= "1.0"?>
<root attr1= "Attribute1" >
<SecondLevel>
<thirdlevel attribute1= "AT1" attribute2= "AT2" >
<ele1 attr1= "AT1" >v</Ele1>
</ThirdLevel>
<thirdlevel attribute1= "att1" attribute2= "Att2" >
<ele1 attr1= "Att1" >va</Ele1>
</ThirdLevel>
<thirdlevel attribute1= "attr1" attribute2= "ATTR2" >
<ele1 attr1= "ATTR1" >val</Ele1>
</ThirdLevel>
</SecondLevel>
</Root>

It is worth mentioning that in practice, the custom namespace [xmlns: ...] method is to use the overloaded method of the XmlSerializer class:

public void Serialize (stream stream, object o, XmlSerializerNamespaces namespaces);

is serialized, where the "namespaces" parameter can be created by the following code:

XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces (
New[] {new XmlQualifiedName (string. Empty, "")});

The use of C # XML serialization and deserialization attributes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.