XmlSerializer Konstruktorok
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Inicializálja a XmlSerializer osztály új példányát.
Túlterhelések
| Name | Description |
|---|---|
| XmlSerializer() |
Inicializálja a XmlSerializer osztály új példányát. |
| XmlSerializer(Type) |
Inicializálja az XmlSerializer osztály új példányát, amely a megadott típusú objektumokat XML-dokumentumokká szerializálhatja, és deszerializálja az XML-dokumentumokat a megadott típusú objektumokká. |
| XmlSerializer(XmlTypeMapping) |
Inicializálja az XmlSerializer osztály egy példányát egy olyan objektummal, amely leképezi az egyik típust egy másikra. |
| XmlSerializer(Type, String) |
Inicializálja az XmlSerializer osztály új példányát, amely a megadott típusú objektumokat XML-dokumentumokká szerializálhatja, és deszerializálja az XML-dokumentumokat a megadott típusú objektumokká. Az összes XML-elem alapértelmezett névterét adja meg. |
| XmlSerializer(Type, Type[]) |
Inicializálja az XmlSerializer osztály új példányát, amely képes a megadott típusú objektumok XML-dokumentumokká való szerializálására, és az XML-dokumentumok deszerializálására egy adott típusú objektumba. Ha egy tulajdonság vagy mező tömböt ad vissza, a |
| XmlSerializer(Type, XmlAttributeOverrides) |
Inicializálja az XmlSerializer osztály új példányát, amely a megadott típusú objektumokat XML-dokumentumokká szerializálhatja, és deszerializálja az XML-dokumentumokat a megadott típusú objektumokká. Minden szerializálandó objektum tartalmazhat osztálypéldányokat, amelyeket ez a túlterhelés felülbírálhat más osztályokkal. |
| XmlSerializer(Type, XmlRootAttribute) |
Inicializálja az XmlSerializer osztály új példányát, amely képes a megadott típusú objektumokat XML-dokumentumokká szerializálni, és deszerializálni egy XML-dokumentumot a megadott típusú objektummá. Emellett megadja az XML-gyökérelemként használni kívánt osztályt is. |
| XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String) |
Inicializálja az osztály új példányát, amely xml-dokumentumpéldányokká szerializálja a XmlSerializer típusobjektumokat Object , és deszerializálja az XML-dokumentumpéldányokat típusobjektumokká Object. Minden szerializálandó objektum tartalmazhat osztálypéldányokat, amelyeket ez a túlterhelés felülír más osztályokkal. Ez a túlterhelés az összes XML-elem alapértelmezett névterét és az XML-gyökérelemként használni kívánt osztályt is meghatározza. |
| XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String) |
Inicializálja az osztály új példányát, amely xml-dokumentumpéldányokká szerializálja a XmlSerializer típusobjektumokat Object , és deszerializálja az XML-dokumentumpéldányokat típusobjektumokká Object. Minden szerializálandó objektum tartalmazhat osztálypéldányokat, amelyeket ez a túlterhelés felülír más osztályokkal. Ez a túlterhelés az összes XML-elem alapértelmezett névterét és az XML-gyökérelemként használni kívánt osztályt is meghatározza. |
| XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence) |
Elavult.
Inicializálja az XmlSerializer osztály új példányát, amely képes a megadott típusú objektumokat XML-dokumentumpéldányokká szerializálni, és deszerializálja az XML-dokumentumpéldányokat a megadott típusú objektumokká. Ez a túlterhelés lehetővé teszi a szerializálási vagy deszerializálási művelet során előforduló egyéb típusokat, valamint az összes XML-elem alapértelmezett névterét, az XML-gyökérelemként használni kívánt osztályt, annak helyét és a hozzáféréshez szükséges hitelesítő adatokat. |
XmlSerializer()
Inicializálja a XmlSerializer osztály új példányát.
protected:
XmlSerializer();
protected XmlSerializer();
Protected Sub New ()
A következőre érvényes:
XmlSerializer(Type)
Inicializálja az XmlSerializer osztály új példányát, amely a megadott típusú objektumokat XML-dokumentumokká szerializálhatja, és deszerializálja az XML-dokumentumokat a megadott típusú objektumokká.
public:
XmlSerializer(Type ^ type);
public XmlSerializer(Type type);
new System.Xml.Serialization.XmlSerializer : Type -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type)
Paraméterek
- type
- Type
A szerializálható objektum XmlSerializer típusa.
Példák
Az alábbi példa egy XmlSerializer olyan objektumot hoz létre, amely szerializál egy nevű Widgetobjektumot. A példa az objektum különböző tulajdonságait állítja be a metódus meghívása Serialize előtt.
private void SerializeObject(string filename)
{
XmlSerializer serializer =
new XmlSerializer(typeof(OrderedItem));
// Create an instance of the class to be serialized.
OrderedItem i = new OrderedItem();
// Set the public property values.
i.ItemName = "Widget";
i.Description = "Regular Widget";
i.Quantity = 10;
i.UnitPrice = (decimal) 2.30;
// Writing the document requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Serialize the object, and close the TextWriter.
serializer.Serialize(writer, i);
writer.Close();
}
// This is the class that will be serialized.
public class OrderedItem
{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
}
Private Sub SerializeObject(ByVal filename As String)
Dim serializer As New XmlSerializer(GetType(OrderedItem))
' Create an instance of the class to be serialized.
Dim i As New OrderedItem()
' Set the public property values.
With i
.ItemName = "Widget"
.Description = "Regular Widget"
.Quantity = 10
.UnitPrice = CDec(2.3)
End With
' Writing the document requires a TextWriter.
Dim writer As New StreamWriter(filename)
' Serialize the object, and close the TextWriter.
serializer.Serialize(writer, i)
writer.Close()
End Sub
' This is the class that will be serialized.
Public Class OrderedItem
Public ItemName As String
Public Description As String
Public UnitPrice As Decimal
Public Quantity As Integer
End Class
Megjegyzések
Az alkalmazások általában több osztályt határoznak meg, amelyeket a XmlSerializer rendszer egyetlen XML-példányú dokumentummá alakít át. A XmlSerializer rendszernek azonban csak egy típust kell ismernie – az XML-gyökérelemet képviselő osztály típusát. Az XmlSerializer automatikusan szerializálja az összes alárendelt osztálypéldányt. Hasonlóképpen csak az XML-gyökérelem típusa szükséges a deszerializáláshoz.
Lásd még
- Serialize(TextWriter, Object)
- Deserialize(Stream)
- XmlAttributes
- Az XML-szerializálás bemutatása
- Útmutató: Alternatív elemnév megadása XML-adatfolyamhoz
- XML-szerializálás szabályozása attribútumokkal
- Példák XML-szerializálásra
- XML-sémadefiníciós eszköz (Xsd.exe)
A következőre érvényes:
XmlSerializer(XmlTypeMapping)
Inicializálja az XmlSerializer osztály egy példányát egy olyan objektummal, amely leképezi az egyik típust egy másikra.
public:
XmlSerializer(System::Xml::Serialization::XmlTypeMapping ^ xmlTypeMapping);
public XmlSerializer(System.Xml.Serialization.XmlTypeMapping xmlTypeMapping);
new System.Xml.Serialization.XmlSerializer : System.Xml.Serialization.XmlTypeMapping -> System.Xml.Serialization.XmlSerializer
Public Sub New (xmlTypeMapping As XmlTypeMapping)
Paraméterek
- xmlTypeMapping
- XmlTypeMapping
Egy XmlTypeMapping olyan típus, amely egy típust egy másikba képez le.
Példák
Az alábbi példa szerializál egy osztályt Group. A , IgnoreThis mezők és az enumerálás tagjai szerializálása GroupNameGroupType felül van bírálva.
CreateOverrideSerializer A metódusban létrejön egy SoapAttributeOverrides objektum, és minden felülírt taghoz vagy számbavételhez létrejön egy SoapAttributes objektum a megfelelő tulajdonságkészlettel, és hozzáadódik az SoapAttributeOverrides objektumhoz. A rendszer létrehoz egy XmlMapping objektumot az SoapAttributeOverrides objektummal, és ezzel XmlMapping az objektummal hozza létre azt, XmlSerializer amely felülbírálja az alapértelmezett szerializálást.
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
public class Group
{
[SoapAttribute (Namespace = "http://www.cpandl.com")]
public string GroupName;
[SoapAttribute(DataType = "base64Binary")]
public Byte [] GroupNumber;
[SoapAttribute(DataType = "date", AttributeName = "CreationDate")]
public DateTime Today;
[SoapElement(DataType = "nonNegativeInteger", ElementName = "PosInt")]
public string PostitiveInt;
// This is ignored when serialized unless it's overridden.
[SoapIgnore]
public bool IgnoreThis;
public GroupType Grouptype;
public Vehicle MyVehicle;
// The SoapInclude allows the method to return a Car.
[SoapInclude(typeof(Car))]
public Vehicle myCar(string licNumber)
{
Vehicle v;
if(licNumber == "")
{
v = new Car();
v.licenseNumber = "!!!!!!";
}
else
{
v = new Car();
v.licenseNumber = licNumber;
}
return v;
}
}
// SoapInclude allows Vehicle to accept Car type.
[SoapInclude(typeof(Car))]
public abstract class Vehicle
{
public string licenseNumber;
public DateTime makeDate;
}
public class Car: Vehicle
{
}
public enum GroupType
{
// These enums can be overridden.
[SoapEnum("Small")]
A,
[SoapEnum("Large")]
B
}
public class Run
{
public static void Main()
{
Run test = new Run();
test.SerializeOriginal("SoapOriginal.xml");
test.SerializeOverride("SoapOverrides.xml");
test.DeserializeOriginal("SoapOriginal.xml");
test.DeserializeOverride("SoapOverrides.xml");
}
public void SerializeOriginal(string filename)
{
// Create an instance of the XmlSerializer class.
XmlTypeMapping myMapping =
(new SoapReflectionImporter().ImportTypeMapping(
typeof(Group)));
XmlSerializer mySerializer =
new XmlSerializer(myMapping);
Group myGroup=MakeGroup();
// Writing the file requires a TextWriter.
XmlTextWriter writer =
new XmlTextWriter(filename, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("wrapper");
// Serialize the class, and close the TextWriter.
mySerializer.Serialize(writer, myGroup);
writer.WriteEndElement();
writer.Close();
}
public void SerializeOverride(string filename)
{
// Create an instance of the XmlSerializer class
// that overrides the serialization.
XmlSerializer overRideSerializer = CreateOverrideSerializer();
Group myGroup=MakeGroup();
// Writing the file requires a TextWriter.
XmlTextWriter writer =
new XmlTextWriter(filename, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("wrapper");
// Serialize the class, and close the TextWriter.
overRideSerializer.Serialize(writer, myGroup);
writer.WriteEndElement();
writer.Close();
}
private Group MakeGroup(){
// Create an instance of the class that will be serialized.
Group myGroup = new Group();
// Set the object properties.
myGroup.GroupName = ".NET";
Byte [] hexByte = new Byte[2]{Convert.ToByte(100),
Convert.ToByte(50)};
myGroup.GroupNumber = hexByte;
DateTime myDate = new DateTime(2002,5,2);
myGroup.Today = myDate;
myGroup.PostitiveInt= "10000";
myGroup.IgnoreThis=true;
myGroup.Grouptype= GroupType.B;
Car thisCar =(Car) myGroup.myCar("1234566");
myGroup.MyVehicle=thisCar;
return myGroup;
}
public void DeserializeOriginal(string filename)
{
// Create an instance of the XmlSerializer class.
XmlTypeMapping myMapping =
(new SoapReflectionImporter().ImportTypeMapping(
typeof(Group)));
XmlSerializer mySerializer =
new XmlSerializer(myMapping);
// Reading the file requires an XmlTextReader.
XmlTextReader reader=
new XmlTextReader(filename);
reader.ReadStartElement("wrapper");
// Deserialize and cast the object.
Group myGroup;
myGroup = (Group) mySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.Close();
}
public void DeserializeOverride(string filename)
{
// Create an instance of the XmlSerializer class.
XmlSerializer overRideSerializer = CreateOverrideSerializer();
// Reading the file requires an XmlTextReader.
XmlTextReader reader=
new XmlTextReader(filename);
reader.ReadStartElement("wrapper");
// Deserialize and cast the object.
Group myGroup;
myGroup = (Group) overRideSerializer.Deserialize(reader);
reader.ReadEndElement();
reader.Close();
ReadGroup(myGroup);
}
private void ReadGroup(Group myGroup){
Console.WriteLine(myGroup.GroupName);
Console.WriteLine(myGroup.GroupNumber[0]);
Console.WriteLine(myGroup.GroupNumber[1]);
Console.WriteLine(myGroup.Today);
Console.WriteLine(myGroup.PostitiveInt);
Console.WriteLine(myGroup.IgnoreThis);
Console.WriteLine();
}
private XmlSerializer CreateOverrideSerializer()
{
SoapAttributeOverrides mySoapAttributeOverrides =
new SoapAttributeOverrides();
SoapAttributes soapAtts = new SoapAttributes();
SoapElementAttribute mySoapElement = new SoapElementAttribute();
mySoapElement.ElementName = "xxxx";
soapAtts.SoapElement = mySoapElement;
mySoapAttributeOverrides.Add(typeof(Group), "PostitiveInt",
soapAtts);
// Override the IgnoreThis property.
SoapIgnoreAttribute myIgnore = new SoapIgnoreAttribute();
soapAtts = new SoapAttributes();
soapAtts.SoapIgnore = false;
mySoapAttributeOverrides.Add(typeof(Group), "IgnoreThis",
soapAtts);
// Override the GroupType enumeration.
soapAtts = new SoapAttributes();
SoapEnumAttribute xSoapEnum = new SoapEnumAttribute();
xSoapEnum.Name = "Over1000";
soapAtts.SoapEnum = xSoapEnum;
// Add the SoapAttributes to the
// mySoapAttributeOverridesrides object.
mySoapAttributeOverrides.Add(typeof(GroupType), "A",
soapAtts);
// Create second enumeration and add it.
soapAtts = new SoapAttributes();
xSoapEnum = new SoapEnumAttribute();
xSoapEnum.Name = "ZeroTo1000";
soapAtts.SoapEnum = xSoapEnum;
mySoapAttributeOverrides.Add(typeof(GroupType), "B",
soapAtts);
// Override the Group type.
soapAtts = new SoapAttributes();
SoapTypeAttribute soapType = new SoapTypeAttribute();
soapType.TypeName = "Team";
soapAtts.SoapType = soapType;
mySoapAttributeOverrides.Add(typeof(Group),soapAtts);
// Create an XmlTypeMapping that is used to create an instance
// of the XmlSerializer. Then return the XmlSerializer object.
XmlTypeMapping myMapping = (new SoapReflectionImporter(
mySoapAttributeOverrides)).ImportTypeMapping(typeof(Group));
XmlSerializer ser = new XmlSerializer(myMapping);
return ser;
}
}
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Xml.Schema
Public Class Group
<SoapAttribute (Namespace:= "http:'www.cpandl.com")> _
Public GroupName As String
<SoapAttribute(DataType:= "base64Binary")> _
Public GroupNumber() As Byte
<SoapAttribute(DataType:= "date", _
AttributeName:= "CreationDate")> _
Public Today As DateTime
<SoapElement(DataType:= "nonNegativeInteger", _
ElementName:= "PosInt")> _
Public PostitiveInt As String
' This is ignored when serialized unless it's overridden.
<SoapIgnore> _
Public IgnoreThis As Boolean
Public Grouptype As GroupType
Public MyVehicle As Vehicle
' The SoapInclude allows the method to return a Car.
<SoapInclude(GetType(Car))> _
Public Function myCar(licNumber As String ) As Vehicle
Dim v As Vehicle
if licNumber = "" Then
v = New Car()
v.licenseNumber = "!!!!!!"
else
v = New Car()
v.licenseNumber = licNumber
End If
return v
End Function
End Class
' SoapInclude allows Vehicle to accept Car type.
<SoapInclude(GetType(Car))> _
Public MustInherit class Vehicle
Public licenseNumber As String
Public makeDate As DateTime
End Class
Public Class Car
Inherits Vehicle
End Class
Public enum GroupType
' These enums can be overridden.
<SoapEnum("Small")> _
A
<SoapEnum("Large")> _
B
End Enum
Public Class Run
Shared Sub Main()
Dim test As Run = New Run()
test.SerializeOriginal("SoapOriginal.xml")
test.SerializeOverride("SoapOverrides.xml")
test.DeserializeOriginal("SoapOriginal.xml")
test.DeserializeOverride("SoapOverrides.xml")
End SUb
Public Sub SerializeOriginal(filename As String)
' Create an instance of the XmlSerializer class.
Dim myMapping As XmlTypeMapping = _
(New SoapReflectionImporter().ImportTypeMapping _
(GetType(Group)))
Dim mySerializer As XmlSerializer = _
New XmlSerializer(myMapping)
Dim myGroup As Group =MakeGroup()
' Writing the file requires a TextWriter.
Dim writer As XmlTextWriter = _
New XmlTextWriter(filename, Encoding.UTF8)
writer.Formatting = Formatting.Indented
writer.WriteStartElement("wrapper")
' Serialize the class, and close the TextWriter.
mySerializer.Serialize(writer, myGroup)
writer.WriteEndElement()
writer.Close()
End Sub
Public Sub SerializeOverride(filename As String)
' Create an instance of the XmlSerializer class
' that overrides the serialization.
Dim overRideSerializer As XmlSerializer = _
CreateOverrideSerializer()
Dim myGroup As Group =MakeGroup()
' Writing the file requires a TextWriter.
Dim writer As XmlTextWriter = _
New XmlTextWriter(filename, Encoding.UTF8)
writer.Formatting = Formatting.Indented
writer.WriteStartElement("wrapper")
' Serialize the class, and close the TextWriter.
overRideSerializer.Serialize(writer, myGroup)
writer.WriteEndElement()
writer.Close()
End Sub
private Function MakeGroup() As Group
' Create an instance of the class that will be serialized.
Dim myGroup As Group = New Group()
' Set the object properties.
myGroup.GroupName = ".NET"
Dim hexByte()As Byte = new Byte(1){Convert.ToByte(100), _
Convert.ToByte(50)}
myGroup.GroupNumber = hexByte
Dim myDate As DateTime = new DateTime(2002,5,2)
myGroup.Today = myDate
myGroup.PostitiveInt = "10000"
myGroup.IgnoreThis = true
myGroup.Grouptype = GroupType.B
Dim thisCar As Car
thisCar =CType(myGroup.myCar("1234566"), Car)
myGroup.myVehicle=thisCar
return myGroup
End Function
Public Sub DeserializeOriginal(filename As String)
' Create an instance of the XmlSerializer class.
Dim myMapping As XmlTypeMapping = _
(New SoapReflectionImporter().ImportTypeMapping _
(GetType(Group)))
Dim mySerializer As XmlSerializer = _
New XmlSerializer(myMapping)
' Reading the file requires an XmlTextReader.
Dim reader As XmlTextReader = _
New XmlTextReader(filename)
reader.ReadStartElement("wrapper")
' Deserialize and cast the object.
Dim myGroup As Group = _
CType(mySerializer.Deserialize(reader), Group)
reader.ReadEndElement()
reader.Close()
End Sub
Public Sub DeserializeOverride(filename As String)
' Create an instance of the XmlSerializer class.
Dim overRideSerializer As XmlSerializer = _
CreateOverrideSerializer()
' Reading the file requires an XmlTextReader.
Dim reader As XmlTextReader = _
New XmlTextReader(filename)
reader.ReadStartElement("wrapper")
' Deserialize and cast the object.
Dim myGroup As Group = _
CType(overRideSerializer.Deserialize(reader), Group)
reader.ReadEndElement()
reader.Close()
ReadGroup(myGroup)
End Sub
private Sub ReadGroup(myGroup As Group)
Console.WriteLine(myGroup.GroupName)
Console.WriteLine(myGroup.GroupNumber(0))
Console.WriteLine(myGroup.GroupNumber(1))
Console.WriteLine(myGroup.Today)
Console.WriteLine(myGroup.PostitiveInt)
Console.WriteLine(myGroup.IgnoreThis)
Console.WriteLine()
End Sub
Private Function CreateOverrideSerializer() As XmlSerializer
Dim soapOver As SoapAttributeOverrides = New SoapAttributeOverrides()
Dim soapAtts As SoapAttributes = New SoapAttributes()
Dim mySoapElement As SoapElementAttribute = New SoapElementAttribute()
mySoapElement.ElementName = "xxxx"
soapAtts.SoapElement = mySoapElement
soapOver.Add(GetType(Group), "PostitiveInt", soapAtts)
' Override the IgnoreThis property.
Dim myIgnore As SoapIgnoreAttribute = new SoapIgnoreAttribute()
soapAtts = New SoapAttributes()
soapAtts.SoapIgnore = false
soapOver.Add(GetType(Group), "IgnoreThis", soapAtts)
' Override the GroupType enumeration.
soapAtts = New SoapAttributes()
Dim xSoapEnum As SoapEnumAttribute = new SoapEnumAttribute()
xSoapEnum.Name = "Over1000"
soapAtts.SoapEnum = xSoapEnum
' Add the SoapAttributes to the SoapOverrides object.
soapOver.Add(GetType(GroupType), "A", soapAtts)
' Create second enumeration and add it.
soapAtts = New SoapAttributes()
xSoapEnum = New SoapEnumAttribute()
xSoapEnum.Name = "ZeroTo1000"
soapAtts.SoapEnum = xSoapEnum
soapOver.Add(GetType(GroupType), "B", soapAtts)
' Override the Group type.
soapAtts = New SoapAttributes()
Dim soapType As SoapTypeAttribute = New SoapTypeAttribute()
soapType.TypeName = "Team"
soapAtts.SoapType = soapType
soapOver.Add(GetType(Group),soapAtts)
Dim myMapping As XmlTypeMapping = (New SoapReflectionImporter( _
soapOver)).ImportTypeMapping(GetType(Group))
Dim ser As XmlSerializer = new XmlSerializer(myMapping)
return ser
End Function
End Class
Megjegyzések
Ez a konstruktor egy objektum SOAP-üzenetbe való szerializálásakor használható XmlSerializer . A létrehozott SOAP-üzenetek szabályozásához használja a névtérben System.Xml.Serialization található speciális attribútumokat (a "Soap" szótól kezdve).
Lásd még
- XmlAttributes
- Az XML-szerializálás bemutatása
- Útmutató: Alternatív elemnév megadása XML-adatfolyamhoz
- XML-szerializálás szabályozása attribútumokkal
- Példák XML-szerializálásra
- XML-sémadefiníciós eszköz (Xsd.exe)
A következőre érvényes:
XmlSerializer(Type, String)
Inicializálja az XmlSerializer osztály új példányát, amely a megadott típusú objektumokat XML-dokumentumokká szerializálhatja, és deszerializálja az XML-dokumentumokat a megadott típusú objektumokká. Az összes XML-elem alapértelmezett névterét adja meg.
public:
XmlSerializer(Type ^ type, System::String ^ defaultNamespace);
public XmlSerializer(Type type, string defaultNamespace);
new System.Xml.Serialization.XmlSerializer : Type * string -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, defaultNamespace As String)
Paraméterek
- type
- Type
A szerializálható objektum XmlSerializer típusa.
- defaultNamespace
- String
Az összes XML-elemhez használandó alapértelmezett névtér.
Példák
Az alábbi példa egy XmlSerializer olyan objektumot hoz létre, amely szerializál egy nevű Widgetobjektumot. A példa az objektum különböző tulajdonságait állítja be a metódus meghívása Serialize előtt.
private void SerializeObject(string filename) {
XmlSerializer serializer = new XmlSerializer
(typeof(OrderedItem), "http://www.cpandl.com");
// Create an instance of the class to be serialized.
OrderedItem i = new OrderedItem();
// Insert code to set property values.
// Writing the document requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Serialize the object, and close the TextWriter
serializer.Serialize(writer, i);
writer.Close();
}
private void DeserializeObject(string filename) {
XmlSerializer serializer = new XmlSerializer
(typeof(OrderedItem), "http://www.cpandl.com");
// 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.
OrderedItem i;
// Deserialize the object.
i = (OrderedItem) serializer.Deserialize(fs);
// Insert code to use the properties and methods of the object.
}
Private Sub SerializeObject(ByVal filename As String)
Dim serializer As New XmlSerializer(GetType(OrderedItem), _
"http://www.cpandl.com")
' Create an instance of the class to be serialized.
Dim i As New OrderedItem()
' Insert code to set property values.
' Writing the document requires a TextWriter.
Dim writer As New StreamWriter(filename)
' Serialize the object, and close the TextWriter.
serializer.Serialize(writer, i)
writer.Close()
End Sub
Private Sub DeserializeObject(ByVal filename As String)
Dim serializer As New XmlSerializer(GetType(OrderedItem), _
"http://www.cpandl.com")
' 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 i As OrderedItem
' Deserialize the object.
i = CType(serializer.Deserialize(fs), OrderedItem)
' Insert code to use the properties and methods of the object.
End Sub
Lásd még
- XmlAttributes
- Az XML-szerializálás bemutatása
- Útmutató: Alternatív elemnév megadása XML-adatfolyamhoz
- XML-szerializálás szabályozása attribútumokkal
- Példák XML-szerializálásra
- XML-sémadefiníciós eszköz (Xsd.exe)
A következőre érvényes:
XmlSerializer(Type, Type[])
Inicializálja az XmlSerializer osztály új példányát, amely képes a megadott típusú objektumok XML-dokumentumokká való szerializálására, és az XML-dokumentumok deszerializálására egy adott típusú objektumba. Ha egy tulajdonság vagy mező tömböt ad vissza, a extraTypes paraméter olyan objektumokat határoz meg, amelyeket be lehet szúrni a tömbbe.
public:
XmlSerializer(Type ^ type, cli::array <Type ^> ^ extraTypes);
public XmlSerializer(Type type, Type[] extraTypes);
new System.Xml.Serialization.XmlSerializer : Type * Type[] -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, extraTypes As Type())
Paraméterek
- type
- Type
A szerializálható objektum XmlSerializer típusa.
Példák
Az alábbi példa egy olyan osztálypéldányt szerializál, amely egy olyan nyilvános mezőt tartalmaz, amely egy objektumtömböt ad vissza. A extraTypes konstruktor paramétere XmlSerializer megadja a tömbben szerializálható objektumok típusait.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
// This defines the object that will be serialized.
public class Teacher
{
public string Name;
public Teacher(){}
/* Note that the Info field returns an array of objects.
Any object can be added to the array by adding the
object type to the array passed to the extraTypes argument. */
[XmlArray (ElementName = "ExtraInfo", IsNullable = true)]
public object[] Info;
public Phone PhoneInfo;
}
// This defines one of the extra types to be included.
public class Address
{
public string City;
public Address(){}
public Address(string city)
{
City = city;
}
}
// Another extra type to include.
public class Phone
{
public string PhoneNumber;
public Phone(){}
public Phone(string phoneNumber)
{
PhoneNumber = phoneNumber;
}
}
// Another type, derived from Phone
public class InternationalPhone:Phone
{
public string CountryCode;
public InternationalPhone(){}
public InternationalPhone(string countryCode)
{
CountryCode = countryCode;
}
}
public class Run
{
public static void Main()
{
Run test = new Run();
test.SerializeObject("Teacher.xml");
test.DeserializeObject("Teacher.xml");
}
private void SerializeObject(string filename)
{
// Writing the file requires a TextWriter.
TextWriter myStreamWriter = new StreamWriter(filename);
// Create a Type array.
Type [] extraTypes= new Type[3];
extraTypes[0] = typeof(Address);
extraTypes[1] = typeof(Phone);
extraTypes[2] = typeof(InternationalPhone);
// Create the XmlSerializer instance.
XmlSerializer mySerializer = new XmlSerializer
(typeof(Teacher),extraTypes);
Teacher teacher = new Teacher();
teacher.Name = "Mike";
// Add extra types to the Teacher object
object [] info = new object[2];
info[0] = new Address("Springville");
info[1] = new Phone("555-0100");
teacher.Info = info;
teacher.PhoneInfo = new InternationalPhone("000");
mySerializer.Serialize(myStreamWriter,teacher);
myStreamWriter.Close();
}
private void DeserializeObject(string filename)
{
// Create a Type array.
Type [] extraTypes= new Type[3];
extraTypes[0] = typeof(Address);
extraTypes[1] = typeof(Phone);
extraTypes[2] = typeof(InternationalPhone);
// Create the XmlSerializer instance.
XmlSerializer mySerializer = new XmlSerializer
(typeof(Teacher),extraTypes);
// Reading a file requires a FileStream.
FileStream fs = new FileStream(filename, FileMode.Open);
Teacher teacher = (Teacher) mySerializer.Deserialize(fs);
// Read the extra information.
Address a = (Address)teacher.Info[0];
Phone p = (Phone) teacher.Info[1];
InternationalPhone Ip =
(InternationalPhone) teacher.PhoneInfo;
Console.WriteLine(teacher.Name);
Console.WriteLine(a.City);
Console.WriteLine(p.PhoneNumber);
Console.WriteLine(Ip.CountryCode);
}
}
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
' This defines the object that will be serialized.
Public Class Teacher
Public Name As String
Public Sub New()
End Sub
' Note that the Info field returns an array of objects.
' Any object can be added to the array by adding the
' object type to the array passed to the extraTypes argument.
<XmlArray(ElementName := "ExtraInfo", IsNullable := True)> _
Public Info() As Object
Public PhoneInfo As Phone
End Class
' This defines one of the extra types to be included.
Public Class Address
Public City As String
Public Sub New()
End Sub
Public Sub New(city As String)
me.City = city
End Sub
End Class
' Another extra type to include.
Public Class Phone
Public PhoneNumber As String
Public Sub New()
End Sub
Public Sub New(phoneNumber As String)
me.PhoneNumber = phoneNumber
End Sub
End Class
' Another type, derived from Phone.
Public Class InternationalPhone
Inherits Phone
Public CountryCode As String
Public Sub New()
End Sub
Public Sub New(countryCode As String)
me.CountryCode = countryCode
End Sub
End Class
Public Class Run
Public Shared Sub Main()
Dim test As New Run()
test.SerializeObject("Teacher.xml")
test.DeserializeObject("Teacher.xml")
End Sub
Private Sub SerializeObject(filename As String)
' Writing the file requires a TextWriter.
Dim myStreamWriter As New StreamWriter(filename)
' Create a Type array.
Dim extraTypes(2) As Type
extraTypes(0) = GetType(Address)
extraTypes(1) = GetType(Phone)
extraTypes(2) = GetType(InternationalPhone)
' Create the XmlSerializer instance.
Dim mySerializer As New XmlSerializer(GetType(Teacher), extraTypes)
Dim teacher As New Teacher()
teacher.Name = "Mike"
' Add extra types to the Teacher object.
Dim info(1) As Object
info(0) = New Address("Springville")
info(1) = New Phone("555-0100")
teacher.Info = info
teacher.PhoneInfo = New InternationalPhone("000")
mySerializer.Serialize(myStreamWriter, teacher)
myStreamWriter.Close()
End Sub
Private Sub DeserializeObject(filename As String)
' Create a Type array.
Dim extraTypes(2) As Type
extraTypes(0) = GetType(Address)
extraTypes(1) = GetType(Phone)
extraTypes(2) = GetType(InternationalPhone)
' Create the XmlSerializer instance.
Dim mySerializer As New XmlSerializer(GetType(Teacher), extraTypes)
' Reading a file requires a FileStream.
Dim fs As New FileStream(filename, FileMode.Open)
Dim teacher As Teacher = CType(mySerializer.Deserialize(fs), Teacher)
' Read the extra information.
Dim a As Address = CType(teacher.Info(0), Address)
Dim p As Phone = CType(teacher.Info(1), Phone)
Dim Ip As InternationalPhone = CType(teacher.PhoneInfo, InternationalPhone)
Console.WriteLine(teacher.Name)
Console.WriteLine(a.City)
Console.WriteLine(p.PhoneNumber)
Console.WriteLine(Ip.CountryCode)
End Sub
End Class
Megjegyzések
Alapértelmezés szerint, ha egy nyilvános tulajdonság vagy mező objektumot vagy objektumtömböt ad vissza, a rendszer automatikusan szerializálja az objektumtípusokat. Ha azonban egy osztály olyan mezőt vagy tulajdonságot tartalmaz, amely egy típusú Objecttömböt ad vissza, bármely objektum beilleszthető ebbe a tömbbe. Ebben az esetben a XmlSerializer rendszernek arra kell utasítania, hogy várja meg a tömbbe Object beszúrt összes lehetséges objektumtípust. Ehhez a extraTypes paraméter használatával adja meg a szerializálni vagy deszerializálni kívánt extra objektumtípusokat.
A paraméterrel megadhatja az extraTypes alaposztályból származtatott típusokat is. Tegyük fel például, hogy létezik egy névvel ellátott Phone alaposztály, és egy névvel ellátott InternationalPhone osztály származik belőle. A paraméter használatával extraTypes adja meg a származtatott típust is.
Lásd még
- XmlAttributes
- Az XML-szerializálás bemutatása
- Útmutató: Alternatív elemnév megadása XML-adatfolyamhoz
- XML-szerializálás szabályozása attribútumokkal
- Példák XML-szerializálásra
- XML-sémadefiníciós eszköz (Xsd.exe)
A következőre érvényes:
XmlSerializer(Type, XmlAttributeOverrides)
Inicializálja az XmlSerializer osztály új példányát, amely a megadott típusú objektumokat XML-dokumentumokká szerializálhatja, és deszerializálja az XML-dokumentumokat a megadott típusú objektumokká. Minden szerializálandó objektum tartalmazhat osztálypéldányokat, amelyeket ez a túlterhelés felülbírálhat más osztályokkal.
public:
XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides);
public XmlSerializer(Type type, System.Xml.Serialization.XmlAttributeOverrides overrides);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides)
Paraméterek
- type
- Type
A szerializálandó objektum típusa.
- overrides
- XmlAttributeOverrides
Példák
Az alábbi példa szerializálja egy DLL-ben definiált osztály egy példányát, és ehhez felülbírálja a DLL-ben található nyilvános tagokat.
// Beginning of HighSchool.dll
namespace HighSchool
{
public class Student
{
public string Name;
public int ID;
}
public class MyClass
{
public Student[] Students;
}
}
namespace College
{
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using HighSchool;
public class Graduate:HighSchool.Student
{
public Graduate(){}
// Add a new field named University.
public string University;
}
public class Run
{
public static void Main()
{
Run test = new Run();
test.WriteOverriddenAttributes("College.xml");
test.ReadOverriddenAttributes("College.xml");
}
private void WriteOverriddenAttributes(string filename)
{
// Writing the file requires a TextWriter.
TextWriter myStreamWriter = new StreamWriter(filename);
// Create an XMLAttributeOverrides class.
XmlAttributeOverrides attrOverrides =
new XmlAttributeOverrides();
// Create the XmlAttributes class.
XmlAttributes attrs = new XmlAttributes();
/* Override the Student class. "Alumni" is the name
of the overriding element in the XML output. */
XmlElementAttribute attr =
new XmlElementAttribute("Alumni", typeof(Graduate));
/* Add the XmlElementAttribute to the collection of
elements in the XmlAttributes object. */
attrs.XmlElements.Add(attr);
/* Add the XmlAttributes to the XmlAttributeOverrides.
"Students" is the name being overridden. */
attrOverrides.Add(typeof(HighSchool.MyClass),
"Students", attrs);
// Create the XmlSerializer.
XmlSerializer mySerializer = new XmlSerializer
(typeof(HighSchool.MyClass), attrOverrides);
MyClass myClass = new MyClass();
Graduate g1 = new Graduate();
g1.Name = "Jackie";
g1.ID = 1;
g1.University = "Alma Mater";
Graduate g2 = new Graduate();
g2.Name = "Megan";
g2.ID = 2;
g2.University = "CM";
Student[] myArray = {g1,g2};
myClass.Students = myArray;
mySerializer.Serialize(myStreamWriter, myClass);
myStreamWriter.Close();
}
private void ReadOverriddenAttributes(string filename)
{
/* The majority of the code here is the same as that in the
WriteOverriddenAttributes method. Because the XML being read
doesn't conform to the schema defined by the DLL, the
XMLAttributesOverrides must be used to create an
XmlSerializer instance to read the XML document.*/
XmlAttributeOverrides attrOverrides = new
XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
XmlElementAttribute attr =
new XmlElementAttribute("Alumni", typeof(Graduate));
attrs.XmlElements.Add(attr);
attrOverrides.Add(typeof(HighSchool.MyClass),
"Students", attrs);
XmlSerializer readSerializer = new XmlSerializer
(typeof(HighSchool.MyClass), attrOverrides);
// To read the file, a FileStream object is required.
FileStream fs = new FileStream(filename, FileMode.Open);
MyClass myClass;
myClass = (MyClass) readSerializer.Deserialize(fs);
/* Here is the difference between reading and writing an
XML document: You must declare an object of the derived
type (Graduate) and cast the Student instance to it.*/
Graduate g;
foreach(Graduate grad in myClass.Students)
{
g = (Graduate) grad;
Console.Write(g.Name + "\t");
Console.Write(g.ID + "\t");
Console.Write(g.University + "\n");
}
}
}
}
' Beginning of HighSchool.dll
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports HighSchool
Namespace HighSchool
Public Class Student
Public Name As String
Public ID As Integer
End Class
Public Class MyClass1
Public Students() As Student
End Class
End Namespace 'HighSchool
Namespace College
Public Class Graduate
Inherits HighSchool.Student
Public Sub New()
End Sub
Public University As String
End Class
Public Class Run
Public Shared Sub Main()
Dim test As New Run()
test.WriteOverriddenAttributes("College.xml")
test.ReadOverriddenAttributes("College.xml")
End Sub
Private Sub WriteOverriddenAttributes(filename As String)
' Writing the file requires a TextWriter.
Dim myStreamWriter As New StreamWriter(filename)
' Create an XMLAttributeOverrides class.
Dim attrOverrides As New XmlAttributeOverrides()
' Create the XmlAttributes class.
Dim attrs As New XmlAttributes()
' Override the Student class. "Alumni" is the name
' of the overriding element in the XML output.
Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
' Add the XmlElementAttribute to the collection of
' elements in the XmlAttributes object.
attrs.XmlElements.Add(attr)
' Add the XmlAttributes to the XmlAttributeOverrides.
' "Students" is the name being overridden.
attrOverrides.Add(GetType(HighSchool.MyClass1), "Students", attrs)
' Create the XmlSerializer.
Dim mySerializer As New XmlSerializer(GetType(HighSchool.MyClass1), attrOverrides)
Dim oMyClass As New MyClass1()
Dim g1 As New Graduate()
g1.Name = "Jackie"
g1.ID = 1
g1.University = "Alma Mater"
Dim g2 As New Graduate()
g2.Name = "Megan"
g2.ID = 2
g2.University = "CM"
Dim myArray As Student() = {g1, g2}
oMyClass.Students = myArray
mySerializer.Serialize(myStreamWriter, oMyClass)
myStreamWriter.Close()
End Sub
Private Sub ReadOverriddenAttributes(filename As String)
' The majority of the code here is the same as that in the
' WriteOverriddenAttributes method. Because the XML being read
' doesn't conform to the schema defined by the DLL, the
' XMLAttributesOverrides must be used to create an
' XmlSerializer instance to read the XML document.
Dim attrOverrides As New XmlAttributeOverrides()
Dim attrs As New XmlAttributes()
Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
attrs.XmlElements.Add(attr)
attrOverrides.Add(GetType(HighSchool.MyClass1), "Students", attrs)
Dim readSerializer As New XmlSerializer(GetType(HighSchool.MyClass1), attrOverrides)
' To read the file, a FileStream object is required.
Dim fs As New FileStream(filename, FileMode.Open)
Dim oMyClass As MyClass1
oMyClass = CType(readSerializer.Deserialize(fs), MyClass1)
' Here is the difference between reading and writing an
' XML document: You must declare an object of the derived
' type (Graduate) and cast the Student instance to it.
Dim g As Graduate
Dim grad As Graduate
For Each grad In oMyClass.Students
g = CType(grad, Graduate)
Console.Write((g.Name & ControlChars.Tab))
Console.Write((g.ID.ToString & ControlChars.Tab))
Console.Write((g.University & ControlChars.Cr))
Next grad
End Sub
End Class
End Namespace 'College
Megjegyzések
A overrides paraméter a mezők és tulajdonságok XML-kódolásának szabályozására használható. Ezek a beállítások felülírják az objektumokon már meglévő attribútumokat. Ez akkor lehet hasznos, ha a forráskód nem módosítható, vagy ugyanazon osztályokhoz több kódolásra van szükség.
Lásd még
- XmlAttributeOverrides
- XmlAttributes
- Az XML-szerializálás bemutatása
- Útmutató: Alternatív elemnév megadása XML-adatfolyamhoz
- XML-szerializálás szabályozása attribútumokkal
- Példák XML-szerializálásra
- XML-sémadefiníciós eszköz (Xsd.exe)
A következőre érvényes:
XmlSerializer(Type, XmlRootAttribute)
Inicializálja az XmlSerializer osztály új példányát, amely képes a megadott típusú objektumokat XML-dokumentumokká szerializálni, és deszerializálni egy XML-dokumentumot a megadott típusú objektummá. Emellett megadja az XML-gyökérelemként használni kívánt osztályt is.
public:
XmlSerializer(Type ^ type, System::Xml::Serialization::XmlRootAttribute ^ root);
public XmlSerializer(Type type, System.Xml.Serialization.XmlRootAttribute root);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlRootAttribute -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, root As XmlRootAttribute)
Paraméterek
- type
- Type
A szerializálható objektum XmlSerializer típusa.
- root
- XmlRootAttribute
Az XmlRootAttribute XML-gyökérelemet jelképező elem.
Példák
Az alábbi példa egy XmlSerializer olyan szerkezetet hoz létre, amely az XML-gyökérelem különböző tulajdonságait, például a névterét és az elem nevét tartalmazza XmlRootAttribute .
private void SerializeObject(string filename) {
// Create an XmlRootAttribute, and set its properties.
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "CustomRoot";
xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;
// Construct the XmlSerializer with the XmlRootAttribute.
XmlSerializer serializer = new XmlSerializer
(typeof(OrderedItem),xRoot);
// Create an instance of the object to serialize.
OrderedItem i = new OrderedItem();
// Insert code to set properties of the ordered item.
// Writing the document requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
serializer.Serialize(writer, i);
writer.Close();
}
private void DeserializeObject(string filename) {
// Create an XmlRootAttribute, and set its properties.
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "CustomRoot";
xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer
(typeof(OrderedItem),xRoot);
// A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);
// Deserialize the object.
OrderedItem i = (OrderedItem) serializer.Deserialize(fs);
// Insert code to use the object's properties and methods.
}
Private Sub SerializeObject(ByVal filename As String)
' Create an XmlRootAttribute, and set its properties.
Dim xRoot As New XmlRootAttribute()
xRoot.ElementName = "CustomRoot"
xRoot.Namespace = "http://www.cpandl.com"
xRoot.IsNullable = True
' Construct the XmlSerializer with the XmlRootAttribute.
Dim serializer As New XmlSerializer(GetType(OrderedItem), xRoot)
' Create an instance of the object to serialize.
Dim i As New OrderedItem()
' Insert code to set properties of the ordered item.
' Writing the document requires a TextWriter.
Dim writer As New StreamWriter(filename)
serializer.Serialize(writer, i)
writer.Close()
End Sub
Private Sub DeserializeObject(ByVal filename As String)
' Create an XmlRootAttribute, and set its properties.
Dim xRoot As New XmlRootAttribute()
xRoot.ElementName = "CustomRoot"
xRoot.Namespace = "http://www.cpandl.com"
xRoot.IsNullable = True
Dim serializer As New XmlSerializer(GetType(OrderedItem), xRoot)
' A FileStream is needed to read the XML document.
Dim fs As New FileStream(filename, FileMode.Open)
' Deserialize the object.
Dim i As OrderedItem = CType(serializer.Deserialize(fs), OrderedItem)
' Insert code to use the object's properties and methods.
End Sub
Megjegyzések
Az XML-dokumentum gyökéreleme az összes többi elemet is magában foglalja. Alapértelmezés szerint a paraméter által type megadott objektum szerializálva lesz gyökérelemként. A tulajdonságok, például a gyökérelem XML-elemének neve, az type objektumból származnak. A root paraméter azonban lehetővé teszi az alapértelmezett objektum adatainak cseréjét egy XmlRootAttribute; az objektum lehetővé teszi egy másik névtér, elemnév stb. beállítását.
Lásd még
- XmlAttributes
- Az XML-szerializálás bemutatása
- Útmutató: Alternatív elemnév megadása XML-adatfolyamhoz
- XML-szerializálás szabályozása attribútumokkal
- Példák XML-szerializálásra
- XML-sémadefiníciós eszköz (Xsd.exe)
A következőre érvényes:
XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)
Inicializálja az osztály új példányát, amely xml-dokumentumpéldányokká szerializálja a XmlSerializer típusobjektumokat Object , és deszerializálja az XML-dokumentumpéldányokat típusobjektumokká Object. Minden szerializálandó objektum tartalmazhat osztálypéldányokat, amelyeket ez a túlterhelés felülír más osztályokkal. Ez a túlterhelés az összes XML-elem alapértelmezett névterét és az XML-gyökérelemként használni kívánt osztályt is meghatározza.
public:
XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides, cli::array <Type ^> ^ extraTypes, System::Xml::Serialization::XmlRootAttribute ^ root, System::String ^ defaultNamespace);
public XmlSerializer(Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides * Type[] * System.Xml.Serialization.XmlRootAttribute * string -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides, extraTypes As Type(), root As XmlRootAttribute, defaultNamespace As String)
Paraméterek
- type
- Type
A szerializálható objektum XmlSerializer típusa.
- overrides
- XmlAttributeOverrides
Olyan XmlAttributeOverrides , amely kibővíti vagy felülbírálja a paraméterben megadott osztály viselkedését type .
- root
- XmlRootAttribute
Az XmlRootAttribute XML-gyökérelem tulajdonságait meghatározó tulajdonság.
- defaultNamespace
- String
Az XML-dokumentum összes XML-elemének alapértelmezett névtere.
Példák
Az alábbi példa szerializál egy DLL-ben definiált osztálypéldányt, és ehhez felülbírálja az osztályban található nyilvános tagokat. A példa emellett további típusok tömbét, az összes XML-elem alapértelmezett névterét és az XML-gyökérelem-információkat biztosító osztályt is meghatározza. A példa azt feltételezi, hogy az elején lévő kód egy DLL-be HighSchoollett lefordítva.
// Beginning of the HighSchool.dll
namespace HighSchool
{
public class Student
{
public string Name;
public int ID;
}
public class MyClass
{
public Student[] Students;
}
}
namespace College
{
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using HighSchool;
public class Graduate:HighSchool.Student
{
public Graduate(){}
// Add a new field named University.
public string University;
// Use extra types to use this field.
public object[]Info;
}
public class Address
{
public string City;
}
public class Phone
{
public string Number;
}
public class Run
{
public static void Main()
{
Run test = new Run();
test.WriteOverriddenAttributes("College.xml");
test.ReadOverriddenAttributes("College.xml");
}
private void WriteOverriddenAttributes(string filename)
{
// Writing the file requires a TextWriter.
TextWriter myStreamWriter = new StreamWriter(filename);
// Create an XMLAttributeOverrides class.
XmlAttributeOverrides attrOverrides =
new XmlAttributeOverrides();
// Create the XmlAttributes class.
XmlAttributes attrs = new XmlAttributes();
/* Override the Student class. "Alumni" is the name
of the overriding element in the XML output. */
XmlElementAttribute attr =
new XmlElementAttribute("Alumni", typeof(Graduate));
/* Add the XmlElementAttribute to the collection of
elements in the XmlAttributes object. */
attrs.XmlElements.Add(attr);
/* Add the XmlAttributes to the XmlAttributeOverrides.
"Students" is the name being overridden. */
attrOverrides.Add(typeof(HighSchool.MyClass),
"Students", attrs);
// Create array of extra types.
Type [] extraTypes = new Type[2];
extraTypes[0]=typeof(Address);
extraTypes[1]=typeof(Phone);
// Create an XmlRootAttribute.
XmlRootAttribute root = new XmlRootAttribute("Graduates");
/* Create the XmlSerializer with the
XmlAttributeOverrides object. */
XmlSerializer mySerializer = new XmlSerializer
(typeof(HighSchool.MyClass), attrOverrides, extraTypes,
root, "http://www.microsoft.com");
MyClass myClass= new MyClass();
Graduate g1 = new Graduate();
g1.Name = "Jacki";
g1.ID = 1;
g1.University = "Alma";
Graduate g2 = new Graduate();
g2.Name = "Megan";
g2.ID = 2;
g2.University = "CM";
Student[] myArray = {g1,g2};
myClass.Students = myArray;
// Create extra information.
Address a1 = new Address();
a1.City = "Ionia";
Address a2 = new Address();
a2.City = "Stamford";
Phone p1 = new Phone();
p1.Number = "555-0101";
Phone p2 = new Phone();
p2.Number = "555-0100";
Object[]o1 = new Object[2]{a1, p1};
Object[]o2 = new Object[2]{a2,p2};
g1.Info = o1;
g2.Info = o2;
mySerializer.Serialize(myStreamWriter,myClass);
myStreamWriter.Close();
}
private void ReadOverriddenAttributes(string filename)
{
/* The majority of the code here is the same as that in the
WriteOverriddenAttributes method. Because the XML being read
doesn't conform to the schema defined by the DLL, the
XMLAttributesOverrides must be used to create an
XmlSerializer instance to read the XML document.*/
XmlAttributeOverrides attrOverrides = new
XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
XmlElementAttribute attr =
new XmlElementAttribute("Alumni", typeof(Graduate));
attrs.XmlElements.Add(attr);
attrOverrides.Add(typeof(HighSchool.MyClass),
"Students", attrs);
Type [] extraTypes = new Type[2];
extraTypes[0] = typeof(Address);
extraTypes[1] = typeof(Phone);
XmlRootAttribute root = new XmlRootAttribute("Graduates");
XmlSerializer readSerializer = new XmlSerializer
(typeof(HighSchool.MyClass), attrOverrides, extraTypes,
root, "http://www.microsoft.com");
// A FileStream object is required to read the file.
FileStream fs = new FileStream(filename, FileMode.Open);
MyClass myClass;
myClass = (MyClass) readSerializer.Deserialize(fs);
/* Here is the difference between reading and writing an
XML document: You must declare an object of the derived
type (Graduate) and cast the Student instance to it.*/
Graduate g;
Address a;
Phone p;
foreach(Graduate grad in myClass.Students)
{
g = (Graduate) grad;
Console.Write(g.Name + "\t");
Console.Write(g.ID + "\t");
Console.Write(g.University + "\n");
a = (Address) g.Info[0];
Console.WriteLine(a.City);
p = (Phone) g.Info[1];
Console.WriteLine(p.Number);
}
}
}
}
'Beginning of the HighSchool.dll
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
' Imports HighSchool
Namespace HighSchool
Public Class Student
Public Name As String
Public ID As Integer
End Class
Public Class ClassRoom
Public Students() As Student
End Class
End Namespace 'HighSchool
Namespace College
Public Class Graduate
Inherits HighSchool.Student
Public Sub New()
End Sub
' Add a new field named University.
Public University As String
' Use extra types to use this field.
Public Info() As Object
End Class
Public Class Address
Public City As String
End Class
Public Class Phone
Public Number As String
End Class
Public Class Run
Public Shared Sub Main()
Dim test As New Run()
test.WriteOverriddenAttributes("College.xml")
test.ReadOverriddenAttributes("College.xml")
End Sub
Private Sub WriteOverriddenAttributes(ByVal filename As String)
' Writing the file requires a TextWriter.
Dim myStreamWriter As New StreamWriter(filename)
' Create an XMLAttributeOverrides class.
Dim attrOverrides As New XmlAttributeOverrides()
' Create the XmlAttributes class.
Dim attrs As New XmlAttributes()
' Override the Student class. "Alumni" is the name
' of the overriding element in the XML output.
Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
' Add the XmlElementAttribute to the collection of
' elements in the XmlAttributes object.
attrs.XmlElements.Add(attr)
' Add the XmlAttributes to the XmlAttributeOverrides.
' "Students" is the name being overridden.
attrOverrides.Add(GetType(HighSchool.ClassRoom), "Students", attrs)
' Create array of extra types.
Dim extraTypes(1) As Type
extraTypes(0) = GetType(Address)
extraTypes(1) = GetType(Phone)
' Create an XmlRootAttribute.
Dim root As New XmlRootAttribute("Graduates")
' Create the XmlSerializer with the
' XmlAttributeOverrides object.
Dim mySerializer As New XmlSerializer(GetType(HighSchool.ClassRoom), _
attrOverrides, extraTypes, root, "http://www.microsoft.com")
Dim oMyClass As New HighSchool.ClassRoom()
Dim g1 As New Graduate()
g1.Name = "Jacki"
g1.ID = 1
g1.University = "Alma"
Dim g2 As New Graduate()
g2.Name = "Megan"
g2.ID = 2
g2.University = "CM"
Dim myArray As HighSchool.Student() = {g1, g2}
oMyClass.Students = myArray
' Create extra information.
Dim a1 As New Address()
a1.City = "Ionia"
Dim a2 As New Address()
a2.City = "Stamford"
Dim p1 As New Phone()
p1.Number = "555-0101"
Dim p2 As New Phone()
p2.Number = "555-0100"
Dim o1() As Object = {a1, p1}
Dim o2() As Object = {a2, p2}
g1.Info = o1
g2.Info = o2
mySerializer.Serialize(myStreamWriter, oMyClass)
myStreamWriter.Close()
End Sub
Private Sub ReadOverriddenAttributes(ByVal filename As String)
' The majority of the code here is the same as that in the
' WriteOverriddenAttributes method. Because the XML being read
' doesn't conform to the schema defined by the DLL, the
' XMLAttributesOverrides must be used to create an
' XmlSerializer instance to read the XML document.
Dim attrOverrides As New XmlAttributeOverrides()
Dim attrs As New XmlAttributes()
Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
attrs.XmlElements.Add(attr)
attrOverrides.Add(GetType(HighSchool.ClassRoom), "Students", attrs)
Dim extraTypes(1) As Type
extraTypes(0) = GetType(Address)
extraTypes(1) = GetType(Phone)
Dim root As New XmlRootAttribute("Graduates")
Dim readSerializer As New XmlSerializer(GetType(HighSchool.ClassRoom), _
attrOverrides, extraTypes, root, "http://www.microsoft.com")
' A FileStream object is required to read the file.
Dim fs As New FileStream(filename, FileMode.Open)
Dim oMyClass As HighSchool.ClassRoom
oMyClass = CType(readSerializer.Deserialize(fs), HighSchool.ClassRoom)
' Here is the difference between reading and writing an
' XML document: You must declare an object of the derived
' type (Graduate) and cast the Student instance to it.
Dim g As Graduate
Dim a As Address
Dim p As Phone
Dim grad As Graduate
For Each grad In oMyClass.Students
g = CType(grad, Graduate)
Console.Write((g.Name & ControlChars.Tab))
Console.Write((g.ID & ControlChars.Tab))
Console.Write((g.University & ControlChars.Cr))
a = CType(g.Info(0), Address)
Console.WriteLine(a.City)
p = CType(g.Info(1), Phone)
Console.WriteLine(p.Number)
Next grad
End Sub
End Class
End Namespace 'College
Megjegyzések
A overrides paraméter lehetővé teszi olyan XmlSerializer osztály létrehozását, amely szerializál egy olyan osztályt, amely kiterjeszti vagy felülírja az alaposztály viselkedését. Egy DLL-hez például létrehozhat egy olyan osztályt, amely örökli vagy kibővíti a DLL-ben található osztályt. Egy ilyen osztály szerializálásához az osztály egy példányát kell használnia a XmlAttributeOverridesXmlSerializer. További részletekért lásd: XmlAttributeOverrides.
Alapértelmezés szerint, ha egy nyilvános tulajdonság vagy mező objektumot vagy objektumtömböt ad vissza, a rendszer automatikusan szerializálja az objektumtípusokat. Ha azonban egy osztály olyan mezőt vagy tulajdonságot tartalmaz, amely egy típusú Objecttömböt ad vissza, bármely objektum beilleszthető ebbe a tömbbe. Ebben az esetben a XmlSerializer rendszernek arra kell utasítania, hogy várja meg a tömbbe Object beszúrt összes lehetséges objektumtípust. Ehhez a extraTypes paraméter használatával adja meg a szerializálni vagy deszerializálni kívánt extra objektumtípusokat.
Az XML-dokumentum gyökéreleme az összes többi elemet is magában foglalja. Alapértelmezés szerint a paraméter által type megadott objektum szerializálva lesz gyökérelemként. A tulajdonságok, például a gyökérelem XML-elemének neve az type objektumból származnak. A root paraméter azonban lehetővé teszi az alapértelmezett objektum adatainak cseréjét egy XmlRootAttribute; az objektum lehetővé teszi egy másik névtér, elemnév stb. beállítását.
A paraméterrel defaultName adja meg a paraméter által létrehozott összes XML-elem alapértelmezett névterét XmlSerializer.
Lásd még
- XmlAttributeOverrides
- XmlRootAttribute
- XmlAttributes
- Az XML-szerializálás bemutatása
- Útmutató: Alternatív elemnév megadása XML-adatfolyamhoz
- XML-szerializálás szabályozása attribútumokkal
- Példák XML-szerializálásra
- XML-sémadefiníciós eszköz (Xsd.exe)
A következőre érvényes:
XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String)
Inicializálja az osztály új példányát, amely xml-dokumentumpéldányokká szerializálja a XmlSerializer típusobjektumokat Object , és deszerializálja az XML-dokumentumpéldányokat típusobjektumokká Object. Minden szerializálandó objektum tartalmazhat osztálypéldányokat, amelyeket ez a túlterhelés felülír más osztályokkal. Ez a túlterhelés az összes XML-elem alapértelmezett névterét és az XML-gyökérelemként használni kívánt osztályt is meghatározza.
public:
XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides, cli::array <Type ^> ^ extraTypes, System::Xml::Serialization::XmlRootAttribute ^ root, System::String ^ defaultNamespace, System::String ^ location);
public XmlSerializer(Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides * Type[] * System.Xml.Serialization.XmlRootAttribute * string * string -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides, extraTypes As Type(), root As XmlRootAttribute, defaultNamespace As String, location As String)
Paraméterek
- type
- Type
A szerializálható objektum XmlSerializer típusa.
- overrides
- XmlAttributeOverrides
Olyan XmlAttributeOverrides , amely kibővíti vagy felülbírálja a paraméterben megadott osztály viselkedését type .
- root
- XmlRootAttribute
Az XmlRootAttribute XML-gyökérelem tulajdonságait meghatározó tulajdonság.
- defaultNamespace
- String
Az XML-dokumentum összes XML-elemének alapértelmezett névtere.
- location
- String
A típusok helye.
A következőre érvényes:
XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)
Figyelemfelhívás
This method is obsolete and will be removed in a future release of the .NET Framework. Please use a XmlSerializer constructor overload which does not take an Evidence parameter. See http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.
Inicializálja az XmlSerializer osztály új példányát, amely képes a megadott típusú objektumokat XML-dokumentumpéldányokká szerializálni, és deszerializálja az XML-dokumentumpéldányokat a megadott típusú objektumokká. Ez a túlterhelés lehetővé teszi a szerializálási vagy deszerializálási művelet során előforduló egyéb típusokat, valamint az összes XML-elem alapértelmezett névterét, az XML-gyökérelemként használni kívánt osztályt, annak helyét és a hozzáféréshez szükséges hitelesítő adatokat.
public:
XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides, cli::array <Type ^> ^ extraTypes, System::Xml::Serialization::XmlRootAttribute ^ root, System::String ^ defaultNamespace, System::String ^ location, System::Security::Policy::Evidence ^ evidence);
public XmlSerializer(Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location, System.Security.Policy.Evidence evidence);
[System.Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use a XmlSerializer constructor overload which does not take an Evidence parameter. See http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.")]
public XmlSerializer(Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location, System.Security.Policy.Evidence evidence);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides * Type[] * System.Xml.Serialization.XmlRootAttribute * string * string * System.Security.Policy.Evidence -> System.Xml.Serialization.XmlSerializer
[<System.Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use a XmlSerializer constructor overload which does not take an Evidence parameter. See http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.")>]
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides * Type[] * System.Xml.Serialization.XmlRootAttribute * string * string * System.Security.Policy.Evidence -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides, extraTypes As Type(), root As XmlRootAttribute, defaultNamespace As String, location As String, evidence As Evidence)
Paraméterek
- type
- Type
A szerializálható objektum XmlSerializer típusa.
- overrides
- XmlAttributeOverrides
Olyan XmlAttributeOverrides , amely kibővíti vagy felülbírálja a paraméterben megadott osztály viselkedését type .
- root
- XmlRootAttribute
Az XmlRootAttribute XML-gyökérelem tulajdonságait meghatározó tulajdonság.
- defaultNamespace
- String
Az XML-dokumentum összes XML-elemének alapértelmezett névtere.
- location
- String
A típusok helye.
- evidence
- Evidence
Az osztály azon példánya, amely a Evidence típusok eléréséhez szükséges hitelesítő adatokat tartalmazza.
- Attribútumok
Megjegyzések
Lehetővé teszi az ideiglenes címtárakhoz való hozzáférés pontosabb ellenőrzését, és megakadályozza a kódinjektálást és -felhasználást. A módszer használatához adjon meg egy helyet, és csak adott felhasználók számára adjon hozzáférést. A rendszergazdák olyan szabályzatokat állíthatnak be bizonyítéklistákkal, amelyek megfelelnek a bizonyítékoknak az engedélyeknek.