XmlTypeAttribute 형식이 serialize 하 여 여는 방법을 제어 하는 데는 XmlSerializer. 형식이 serialize 될 때 예를 들어, 기본적으로는 XmlSerializer 클래스 이름을 XML 요소 이름으로 사용 합니다.만들어는 XmlTypeAttribute설정에서 XmlType 속성, 및 만들기는 XmlAttributeOverrides 개체는 XML 요소 이름을 변경할 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.IO; namespace xml_test03 { public class Transportation { public Car[] Cars; } public class Car { public int ID; } class Program { static void Main(string[] args) { Program t = new Program(); t.SerializeObject("XmlType.xml"); } // Return an XmlSerializer used for overriding. public XmlSerializer CreateOverrider() { // Create the XmlAttributes and XmlAttributeOverrides objects. XmlAttributes attrs = new XmlAttributes(); XmlAttributeOverrides xOver = new XmlAttributeOverrides(); /* Create an XmlTypeAttribute and change the name of the XML type. */ XmlTypeAttribute xType = new XmlTypeAttribute(); xType.TypeName = "Autos"; // Set the XmlTypeAttribute to the XmlType property. attrs.XmlType = xType; /* Add the XmlAttributes to the XmlAttributeOverrides, specifying the member to override. */ xOver.Add(typeof(Car), attrs); // Create the XmlSerializer, and return it. XmlSerializer xSer = new XmlSerializer (typeof(Transportation), xOver); return xSer; } public void SerializeObject(string filename) { // Create an XmlSerializer instance. XmlSerializer xSer = CreateOverrider(); // Create object and serialize it. Transportation myTransportation = new Transportation(); Car c1 = new Car(); c1.ID = 12; Car c2 = new Car(); c2.ID = 44; myTransportation.Cars = new Car[2] { c1, c2 }; // To write the file, a TextWriter is required. TextWriter writer = new StreamWriter(filename); xSer.Serialize(writer, myTransportation); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <Transportation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Cars> <Autos> <ID>12</ID> </Autos> <Autos> <ID>44</ID> </Autos> </Cars> </Transportation> |