XmlSerializer 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
XML 문서로 개체를 직렬화하고 역직렬화합니다. 개체 XmlSerializer 를 XML로 인코딩하는 방법을 제어할 수 있습니다.
public ref class XmlSerializer
public class XmlSerializer
type XmlSerializer = class
Public Class XmlSerializer
- 상속
-
XmlSerializer
예제
다음 예제에서는 두 가지 기본 클래스를 포함합니다. PurchaseOrderTest 클래스에는 PurchaseOrder 단일 구매에 대한 정보가 포함되어 있습니다. 클래스에는 Test 구매 주문을 만들고 만든 구매 주문을 읽는 메서드가 포함됩니다.
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
/* The XmlRootAttribute allows you to set an alternate name
(PurchaseOrder) of the XML element, the element namespace; by
default, the XmlSerializer uses the class name. The attribute
also allows you to set the XML namespace for the element. Lastly,
the attribute sets the IsNullable property, which specifies whether
the xsi:null attribute appears if the class instance is set to
a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
public Address ShipTo;
public string OrderDate;
/* The XmlArrayAttribute changes the XML element name
from the default of "OrderedItems" to "Items". */
[XmlArrayAttribute("Items")]
public OrderedItem[] OrderedItems;
public decimal SubTotal;
public decimal ShipCost;
public decimal TotalCost;
}
public class Address
{
/* The XmlAttribute instructs the XmlSerializer to serialize the Name
field as an XML attribute instead of an XML element (the default
behavior). */
[XmlAttribute]
public string Name;
public string Line1;
/* Setting the IsNullable property to false instructs the
XmlSerializer that the XML attribute will not appear if
the City field is set to a null reference. */
[XmlElementAttribute(IsNullable = false)]
public string City;
public string State;
public string Zip;
}
public class OrderedItem
{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
public decimal LineTotal;
/* Calculate is a custom method that calculates the price per item,
and stores the value in a field. */
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}
public class Test
{
public static void Main()
{
// Read and write purchase orders.
Test t = new Test();
t.CreatePO("po.xml");
t.ReadPO("po.xml");
}
private void CreatePO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(typeof(PurchaseOrder));
TextWriter writer = new StreamWriter(filename);
PurchaseOrder po=new PurchaseOrder();
// Create an address to ship and bill to.
Address billAddress = new Address();
billAddress.Name = "Teresa Atkinson";
billAddress.Line1 = "1 Main St.";
billAddress.City = "AnyTown";
billAddress.State = "WA";
billAddress.Zip = "00000";
// Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress;
po.OrderDate = System.DateTime.Now.ToLongDateString();
// Create an OrderedItem object.
OrderedItem i1 = new OrderedItem();
i1.ItemName = "Widget S";
i1.Description = "Small widget";
i1.UnitPrice = (decimal) 5.23;
i1.Quantity = 3;
i1.Calculate();
// Insert the item into the array.
OrderedItem [] items = {i1};
po.OrderedItems = items;
// Calculate the total cost.
decimal subTotal = new decimal();
foreach(OrderedItem oi in items)
{
subTotal += oi.LineTotal;
}
po.SubTotal = subTotal;
po.ShipCost = (decimal) 12.51;
po.TotalCost = po.SubTotal + po.ShipCost;
// Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
}
protected void ReadPO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to be deserialized.
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
/* If the XML document has been altered with unknown
nodes or attributes, handle them with the
UnknownNode and UnknownAttribute events.*/
serializer.UnknownNode+= new
XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute+= new
XmlAttributeEventHandler(serializer_UnknownAttribute);
// A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);
// Declare an object variable of the type to be deserialized.
PurchaseOrder po;
/* Use the Deserialize method to restore the object's state with
data from the XML document. */
po = (PurchaseOrder) serializer.Deserialize(fs);
// Read the order date.
Console.WriteLine ("OrderDate: " + po.OrderDate);
// Read the shipping address.
Address shipTo = po.ShipTo;
ReadAddress(shipTo, "Ship To:");
// Read the list of ordered items.
OrderedItem [] items = po.OrderedItems;
Console.WriteLine("Items to be shipped:");
foreach(OrderedItem oi in items)
{
Console.WriteLine("\t"+
oi.ItemName + "\t" +
oi.Description + "\t" +
oi.UnitPrice + "\t" +
oi.Quantity + "\t" +
oi.LineTotal);
}
// Read the subtotal, shipping cost, and total cost.
Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
}
protected void ReadAddress(Address a, string label)
{
// Read the fields of the Address object.
Console.WriteLine(label);
Console.WriteLine("\t"+ a.Name );
Console.WriteLine("\t" + a.Line1);
Console.WriteLine("\t" + a.City);
Console.WriteLine("\t" + a.State);
Console.WriteLine("\t" + a.Zip );
Console.WriteLine();
}
private void serializer_UnknownNode
(object sender, XmlNodeEventArgs e)
{
Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
}
private void serializer_UnknownAttribute
(object sender, XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.Attr;
Console.WriteLine("Unknown attribute " +
attr.Name + "='" + attr.Value + "'");
}
}
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
' The XmlRootAttribute allows you to set an alternate name
' (PurchaseOrder) of the XML element, the element namespace; by
' default, the XmlSerializer uses the class name. The attribute
' also allows you to set the XML namespace for the element. Lastly,
' the attribute sets the IsNullable property, which specifies whether
' the xsi:null attribute appears if the class instance is set to
' a null reference.
<XmlRootAttribute("PurchaseOrder", _
Namespace := "http://www.cpandl.com", IsNullable := False)> _
Public Class PurchaseOrder
Public ShipTo As Address
Public OrderDate As String
' The XmlArrayAttribute changes the XML element name
' from the default of "OrderedItems" to "Items".
<XmlArrayAttribute("Items")> _
Public OrderedItems() As OrderedItem
Public SubTotal As Decimal
Public ShipCost As Decimal
Public TotalCost As Decimal
End Class
Public Class Address
' The XmlAttribute instructs the XmlSerializer to serialize the Name
' field as an XML attribute instead of an XML element (the default
' behavior).
<XmlAttribute()> _
Public Name As String
Public Line1 As String
' Setting the IsNullable property to false instructs the
' XmlSerializer that the XML attribute will not appear if
' the City field is set to a null reference.
<XmlElementAttribute(IsNullable := False)> _
Public City As String
Public State As String
Public Zip As String
End Class
Public Class OrderedItem
Public ItemName As String
Public Description As String
Public UnitPrice As Decimal
Public Quantity As Integer
Public LineTotal As Decimal
' Calculate is a custom method that calculates the price per item,
' and stores the value in a field.
Public Sub Calculate()
LineTotal = UnitPrice * Quantity
End Sub
End Class
Public Class Test
Public Shared Sub Main()
' Read and write purchase orders.
Dim t As New Test()
t.CreatePO("po.xml")
t.ReadPO("po.xml")
End Sub
Private Sub CreatePO(filename As String)
' Create an instance of the XmlSerializer class;
' specify the type of object to serialize.
Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
Dim writer As New StreamWriter(filename)
Dim po As New PurchaseOrder()
' Create an address to ship and bill to.
Dim billAddress As New Address()
billAddress.Name = "Teresa Atkinson"
billAddress.Line1 = "1 Main St."
billAddress.City = "AnyTown"
billAddress.State = "WA"
billAddress.Zip = "00000"
' Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress
po.OrderDate = System.DateTime.Now.ToLongDateString()
' Create an OrderedItem object.
Dim i1 As New OrderedItem()
i1.ItemName = "Widget S"
i1.Description = "Small widget"
i1.UnitPrice = CDec(5.23)
i1.Quantity = 3
i1.Calculate()
' Insert the item into the array.
Dim items(0) As OrderedItem
items(0) = i1
po.OrderedItems = items
' Calculate the total cost.
Dim subTotal As New Decimal()
Dim oi As OrderedItem
For Each oi In items
subTotal += oi.LineTotal
Next oi
po.SubTotal = subTotal
po.ShipCost = CDec(12.51)
po.TotalCost = po.SubTotal + po.ShipCost
' Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po)
writer.Close()
End Sub
Protected Sub ReadPO(filename As String)
' Create an instance of the XmlSerializer class;
' specify the type of object to be deserialized.
Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
' If the XML document has been altered with unknown
' nodes or attributes, handle them with the
' UnknownNode and UnknownAttribute events.
AddHandler serializer.UnknownNode, AddressOf serializer_UnknownNode
AddHandler serializer.UnknownAttribute, AddressOf serializer_UnknownAttribute
' A FileStream is needed to read the XML document.
Dim fs As New FileStream(filename, FileMode.Open)
' Declare an object variable of the type to be deserialized.
Dim po As PurchaseOrder
' Use the Deserialize method to restore the object's state with
' data from the XML document.
po = CType(serializer.Deserialize(fs), PurchaseOrder)
' Read the order date.
Console.WriteLine(("OrderDate: " & po.OrderDate))
' Read the shipping address.
Dim shipTo As Address = po.ShipTo
ReadAddress(shipTo, "Ship To:")
' Read the list of ordered items.
Dim items As OrderedItem() = po.OrderedItems
Console.WriteLine("Items to be shipped:")
Dim oi As OrderedItem
For Each oi In items
Console.WriteLine((ControlChars.Tab & oi.ItemName & ControlChars.Tab & _
oi.Description & ControlChars.Tab & oi.UnitPrice & ControlChars.Tab & _
oi.Quantity & ControlChars.Tab & oi.LineTotal))
Next oi
' Read the subtotal, shipping cost, and total cost.
Console.WriteLine(( New String(ControlChars.Tab, 5) & _
" Subtotal" & ControlChars.Tab & po.SubTotal))
Console.WriteLine(New String(ControlChars.Tab, 5) & _
" Shipping" & ControlChars.Tab & po.ShipCost )
Console.WriteLine( New String(ControlChars.Tab, 5) & _
" Total" & New String(ControlChars.Tab, 2) & po.TotalCost)
End Sub
Protected Sub ReadAddress(a As Address, label As String)
' Read the fields of the Address object.
Console.WriteLine(label)
Console.WriteLine(ControlChars.Tab & a.Name)
Console.WriteLine(ControlChars.Tab & a.Line1)
Console.WriteLine(ControlChars.Tab & a.City)
Console.WriteLine(ControlChars.Tab & a.State)
Console.WriteLine(ControlChars.Tab & a.Zip)
Console.WriteLine()
End Sub
Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
End Sub
Private Sub serializer_UnknownAttribute(sender As Object, e As XmlAttributeEventArgs)
Dim attr As System.Xml.XmlAttribute = e.Attr
Console.WriteLine(("Unknown attribute " & attr.Name & "='" & attr.Value & "'"))
End Sub
End Class
설명
이 API에 대한 자세한 내용은 XmlSerializer에 대한 추가 API 비고를 참조하세요.
생성자
| Name | Description |
|---|---|
| XmlSerializer() |
XmlSerializer 클래스의 새 인스턴스를 초기화합니다. |
| XmlSerializer(Type, String) |
지정된 형식의 XmlSerializer 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 클래스의 새 인스턴스를 초기화합니다. 모든 XML 요소의 기본 네임스페이스를 지정합니다. |
| XmlSerializer(Type, Type[]) |
지정된 형식의 XmlSerializer 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 클래스의 새 인스턴스를 초기화합니다. 속성 또는 필드가 배열을 반환하는 경우 매개 변수는 |
| XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence) |
사용되지 않음.
지정된 형식의 XmlSerializer 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 지정된 형식의 개체로 역직렬화할 수 있는 클래스의 새 인스턴스를 초기화합니다. 이 오버로드를 사용하면 직렬화 또는 역직렬화 작업 중에 발생할 수 있는 다른 형식뿐만 아니라 모든 XML 요소에 대한 기본 네임스페이스, XML 루트 요소로 사용할 클래스, 해당 위치 및 액세스에 필요한 자격 증명을 제공할 수 있습니다. |
| XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String) |
형식의 XmlSerializer 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 형식 Object 의 개체로 역직렬화할 수 있는 클래스의 Object새 인스턴스를 초기화합니다. serialize할 각 개체 자체에는 클래스 인스턴스가 포함될 수 있으며, 이 인스턴스는 이 오버로드가 다른 클래스와 재정의됩니다. 또한 이 오버로드는 XML 루트 요소로 사용할 모든 XML 요소 및 클래스의 기본 네임스페이스를 지정합니다. |
| XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String) |
형식의 XmlSerializer 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 형식 Object 의 개체로 역직렬화할 수 있는 클래스의 Object새 인스턴스를 초기화합니다. serialize할 각 개체 자체에는 클래스 인스턴스가 포함될 수 있으며, 이 인스턴스는 이 오버로드가 다른 클래스와 재정의됩니다. 또한 이 오버로드는 XML 루트 요소로 사용할 모든 XML 요소 및 클래스의 기본 네임스페이스를 지정합니다. |
| XmlSerializer(Type, XmlAttributeOverrides) |
지정된 형식의 XmlSerializer 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 클래스의 새 인스턴스를 초기화합니다. serialize할 각 개체에는 클래스 인스턴스가 포함될 수 있으며, 이 오버로드는 다른 클래스와 재정의할 수 있습니다. |
| XmlSerializer(Type, XmlRootAttribute) |
지정된 형식의 XmlSerializer 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 클래스의 새 인스턴스를 초기화합니다. 또한 XML 루트 요소로 사용할 클래스를 지정합니다. |
| XmlSerializer(Type) |
지정된 형식의 XmlSerializer 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 클래스의 새 인스턴스를 초기화합니다. |
| XmlSerializer(XmlTypeMapping) |
한 형식을 다른 형식에 XmlSerializer 매핑하는 개체를 사용하여 클래스의 인스턴스를 초기화합니다. |
메서드
| Name | Description |
|---|---|
| CanDeserialize(XmlReader) |
지정된 XML 문서를 역직렬화할 XmlSerializer 수 있는지 여부를 나타내는 값을 가져옵니다. |
| CreateReader() |
serialize할 XML 문서를 읽는 데 사용되는 개체를 반환합니다. |
| CreateWriter() |
파생 클래스에서 재정의되는 경우 개체를 serialize하는 데 사용되는 기록기를 반환합니다. |
| Deserialize(Stream) |
지정된 Stream문서에 포함된 XML 문서를 역직렬화합니다. |
| Deserialize(TextReader) |
지정된 TextReader문서에 포함된 XML 문서를 역직렬화합니다. |
| Deserialize(XmlReader, String, XmlDeserializationEvents) |
지정된 에 포함된 데이터를 사용하여 개체를 역직렬화합니다 XmlReader. |
| Deserialize(XmlReader, String) |
지정 XmlReader 한 인코딩 스타일에 포함된 XML 문서를 역직렬화합니다. |
| Deserialize(XmlReader, XmlDeserializationEvents) |
지정된 XmlReader 문서에 포함된 XML 문서를 역직렬화하고 역직렬화 중에 발생하는 이벤트를 재정의할 수 있도록 합니다. |
| Deserialize(XmlReader) |
지정된 XmlReader문서에 포함된 XML 문서를 역직렬화합니다. |
| Deserialize(XmlSerializationReader) |
지정된 XmlSerializationReader문서에 포함된 XML 문서를 역직렬화합니다. |
| Equals(Object) |
지정한 개체와 현재 개체가 같은지 여부를 확인합니다. (다음에서 상속됨 Object) |
| FromMappings(XmlMapping[], Evidence) |
사용되지 않음.
한 XML 형식의 XmlSerializer 매핑에서 다른 XML 형식으로 만든 클래스의 인스턴스를 반환합니다. |
| FromMappings(XmlMapping[], Type) |
지정된 매핑에서 클래스의 XmlSerializer 인스턴스를 반환합니다. |
| FromMappings(XmlMapping[]) |
개체 배열 XmlSerializer 에서 만든 개체의 XmlTypeMapping 배열을 반환합니다. |
| FromTypes(Type[]) |
형식 배열 XmlSerializer 에서 만든 개체의 배열을 반환합니다. |
| GenerateSerializer(Type[], XmlMapping[], CompilerParameters) |
지정된 매핑 및 컴파일러 설정 및 옵션을 사용하여 지정된 형식 또는 형식을 직렬화하거나 역직렬화하는 데 사용되는 사용자 지정 직렬 변환기가 포함된 어셈블리를 반환합니다. |
| GenerateSerializer(Type[], XmlMapping[]) |
지정된 매핑을 사용하여 지정된 형식 또는 형식을 직렬화하거나 역직렬화하는 데 사용되는 사용자 지정 직렬 변환기가 포함된 어셈블리를 반환합니다. |
| GetHashCode() |
기본 해시 함수로 작동합니다. (다음에서 상속됨 Object) |
| GetType() |
현재 인스턴스의 Type 가져옵니다. (다음에서 상속됨 Object) |
| GetXmlSerializerAssemblyName(Type, String) |
지정된 네임스페이스에서 지정된 형식에 대한 serializer를 포함하는 어셈블리의 이름을 반환합니다. |
| GetXmlSerializerAssemblyName(Type) |
지정된 형식을 직렬화하거나 역직렬화하기 위해 특별히 만든 하나 이상의 버전을 포함하는 어셈블리의 XmlSerializer 이름을 반환합니다. |
| MemberwiseClone() |
현재 Object단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
| Serialize(Object, XmlSerializationWriter) |
지정된 문서를 직렬화하고 지정된 Object 문서를 사용하여 XmlSerializationWriterXML 문서를 파일에 씁니다. |
| Serialize(Stream, Object, XmlSerializerNamespaces) |
지정된 Object 네임스페이스를 참조하는 지정된 Stream 문서를 사용하여 지정된 문서를 serialize하고 XML 문서를 파일에 씁니다. |
| Serialize(Stream, Object) | |
| Serialize(TextWriter, Object, XmlSerializerNamespaces) |
지정 Object 한 문서를 직렬화하고 지정된 TextWriter 네임스페이스를 사용하여 XML 문서를 파일에 쓰고 지정한 네임스페이스를 참조합니다. |
| Serialize(TextWriter, Object) |
지정된 문서를 직렬화하고 지정된 Object 문서를 사용하여 TextWriterXML 문서를 파일에 씁니다. |
| Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) |
지정한 Object 문서를 직렬화하고 지정된 XmlWriterXML 네임스페이스 및 인코딩을 사용하여 XML 문서를 파일에 씁니다. |
| Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) |
지정된 개체를 직렬화하고 지정된 개체를 사용하여 XmlWriter XML 문서를 파일에 쓰고 지정된 네임스페이스 및 인코딩 스타일을 참조합니다. |
| Serialize(XmlWriter, Object, XmlSerializerNamespaces) |
지정 Object 한 문서를 직렬화하고 지정된 XmlWriter 네임스페이스를 사용하여 XML 문서를 파일에 쓰고 지정한 네임스페이스를 참조합니다. |
| Serialize(XmlWriter, Object) | |
| ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |
이벤트
| Name | Description |
|---|---|
| UnknownAttribute |
XmlSerializer 역직렬화하는 동안 알 수 없는 형식의 XML 특성이 발견되면 발생합니다. |
| UnknownElement |
역직렬화하는 동안 알 수 없는 형식의 XML 요소가 발견될 때 XmlSerializer 발생합니다. |
| UnknownNode |
역직렬화하는 동안 알 수 없는 형식의 XML 노드가 발견될 때 XmlSerializer 발생합니다. |
| UnreferencedObject |
SOAP로 인코딩된 XML 스트림을 역직렬화하는 동안 사용되지 않거나 참조되지 않는 인식된 형식이 발견될 때 XmlSerializer 발생합니다. |
적용 대상
스레드 보안
이 형식은 스레드로부터 안전합니다.