using System; using System.Xml.Serialization; class Program { [XmlRoot("Person")] class Person { [XmlElement("Name")] public string Name { get; set; } [XmlElement("Age")] public int Age { get; set; } } static void Main() { // 对象转 XML Person person = new Person { Name = "Alice", Age = 25 }; XmlSerializer serializer = new XmlSerializer(typeof(Person)); using (StringWriter writer = new StringWriter()) { serializer.Serialize(writer, person); string xml = writer.ToString(); Console.WriteLine(xml); } // XML 转对象 string xmlData = "<person><name>Bob</name><age>30</age></person>"; using (StringReader reader = new StringReader(xmlData)) { Person deserializedPerson = (Person)serializer.Deserialize(reader); Console.WriteLine(deserializedPerson.Name + " " + deserializedPerson.Age); } } }
推荐阅读