在C#中,使用XML序列化处理复杂对象主要涉及到以下几个方面:
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
类将复杂对象序列化为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字符串反序列化为复杂对象。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);
通过以上步骤,你可以实现复杂对象的XML序列化和反序列化。注意,在处理更复杂的对象时,可能需要处理继承、抽象类、接口等高级概念。在这些情况下,你可能需要使用XmlInclude
、XmlType
等特性来指定相关类型。