在C#中,使用XML序列化處理復(fù)雜對象主要涉及到以下幾個方面:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
public List<string> Hobbies { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
XmlElement
、XmlAttribute
、XmlRoot
等特性。[XmlRoot("Person")]
public class Person
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Age")]
public int Age { get; set; }
[XmlElement("Address")]
public Address Address { get; set; }
[XmlElement("Hobbies")]
public List<string> Hobbies { get; set; }
}
[XmlRoot("Address")]
public class Address
{
[XmlElement("Street")]
public string Street { get; set; }
[XmlElement("City")]
public string City { get; set; }
[XmlElement("PostalCode")]
public string PostalCode { get; set; }
}
XmlSerializer
類將復(fù)雜對象序列化為XML字符串。Person person = new Person
{
Name = "John Doe",
Age = 30,
Address = new Address
{
Street = "123 Main St",
City = "New York",
PostalCode = "10001"
},
Hobbies = new List<string> { "Reading", "Traveling" }
};
XmlSerializer serializer = new XmlSerializer(typeof(Person));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, person);
string xmlString = writer.ToString();
XmlSerializer
類將XML字符串反序列化為復(fù)雜對象。string xmlString =<Person><Name>John Doe</Name><Age>30</Age<Address><Street>123 Main St</Street><City>New York</City><PostalCode>10001</PostalCode></Address><Hobbies<string>Reading</string<string>Traveling</string></Hobbies></Person>";
XmlSerializer serializer = new XmlSerializer(typeof(Person));
StringReader reader = new StringReader(xmlString);
Person deserializedPerson = (Person)serializer.Deserialize(reader);
通過以上步驟,你可以實(shí)現(xiàn)復(fù)雜對象的XML序列化和反序列化。注意,在處理更復(fù)雜的對象時,可能需要處理繼承、抽象類、接口等高級概念。在這些情況下,你可能需要使用XmlInclude
、XmlType
等特性來指定相關(guān)類型。