백엔드 개발 XML/RSS 튜토리얼 XML 직렬화 샘플 코드 공유

XML 직렬화 샘플 코드 공유

Mar 22, 2017 pm 05:16 PM

직렬화는 Object를 전송에 사용할 수 있는 형식으로 변환하는 것입니다. 예: 객체를 직렬화하고 클라이언트 측과 서버 측에서 Http를 사용하여 인터넷을 통해 전달할 수 있습니다. 반대쪽에서 역직렬화를 사용하여 스트림을 객체로 변환할 수 있습니다.

 XML 직렬화 (XML 직렬화) 공개 필드와 속성만 직렬화합니다. XML 직렬화에는 유형 정보가 포함되지 않습니다. XML은 데이터 설명 및 관계 등급 지정에 탁월한 메커니즘을 갖고 있으므로 의 직렬화 정보를 저장하는 데 적합합니다. 참고: XML 직렬화는 메서드, 인덱서 및 private.
필드 또는 읽기 전용 속성(읽기 전용 컬렉션 제외)을 변환하지 않습니다. private, XML 직렬화 대신
BinaryFormatter를 사용하세요. 다음은 XML 직렬화를 사용하는 예입니다.

DataSet 직렬화

private void SerializeDataSet(string filename){
    XmlSerializer ser = new XmlSerializer(typeof(DataSet));
        
    // Creates a DataSet; adds a table, column, and ten rows.
    DataSet ds = new DataSet("myDataSet");
    DataTable t = new DataTable("table1");
    DataColumn c = new DataColumn("thing");
    t.Columns.Add(c);
    ds.Tables.Add(t);
    DataRow r;
    for(int i = 0; i<10;i++){
        r = t.NewRow();
        r[0] = "Thing " + i;
        t.Rows.Add(r);
    }
    TextWriter writer = new StreamWriter(filename);
    ser.Serialize(writer, ds);
    writer.Close();
}
로그인 후 복사
---------

XmlElement 및 XmlNode 직렬화


아아아아------------------------- -- --------

직렬화에는 복잡한 객체(객체)를 반환하는 클래스가 포함되어 있습니다. (
클래스
) 필드가 (필드) 및 속성(속성)은 복잡한 개체(예: 배열
또는 클래스 인스턴스)를 반환합니다. XmlSerializer는 이를 기본 XML 문서에 중첩된 요소로 변환합니다. 두 번째 클래스의 인스턴스입니다.

직렬화된 출력 XML은 다음과 유사합니다

public class PurchaseOrder
{
    public Address MyAddress;
}
public class Address
{
    public string FirstName;
}
로그인 후 복사

---------- ----- ----------------------

직렬화 객체(객체)큐


객체 큐를 반환하는 필드(필드)를 직렬화할 수 있습니다

<PurchaseOrder>
    <Address>
        <FirstName>George</FirstName>
    </Address>
</PurchaseOrder>
로그인 후 복사

직렬화된 출력 XML은 다음과 유사합니다.

public class PurchaseOrder
{
    public Item [] ItemsOrders
}
public class Item
{
    public string ItemID
    public decimal ItemPrice
}
로그인 후 복사

-- -------------------- ---- ----------------------

ICollection

인터페이스
를 구현하는 클래스 직렬화 ICollection
인터페이스를 동시에 구현하여 컬렉션 클래스를 생성하고
XmlSerializer를 사용하여 클래스의 인스턴스를 직렬화할 수 있습니다. 클래스가 ICollection을 구현할 때 주의하세요. 인터페이스를 사용하면 클래스에 포함된 컬렉션만 직렬화되고 클래스에 추가된 다른 필드와 속성은 직렬화되지 않습니다. 직렬화된 클래스에는 Add method 및 Item 속성이 포함되어야 합니다. (C#의 인덱서).


참고: 직렬화된 강력한 형식의 컬렉션 클래스를 설계하고 사용할 때 다음 사항에 주의해야 합니다.

규칙의 제한으로 인해 귀하의 클래스는 귀하의 클래스(컬렉션) 유형의 컬렉션(배열)에 포함된 컬렉션으로 직렬화됩니다. 즉, 추가 속성(속성)을 추가하면 해당 클래스는 포함되지 않습니다. 예:




XML 직렬화 샘플 코드 공유


여기
고객 계정는 직렬화되지만 하나의계정개체이름, 주소 및 기타 필드의 컬렉션은 하나로 직렬화됩니다. 확실한 해결책은 다음과 같습니다:

这里时MSDN对它的介绍:

XmlSerializer can process classes that implement IEnumerable or ICollection differently if they meet certain requirements. A class that implements IEnumerable must implement a public Add method that takes a single parameter. The Add method's parameter must be consistent (polymorphic) with the type returned from the IEnumerator.Current property returned from the GetEnumerator method. A class that implements ICollection in addition to IEnumerable (such as CollectionBase) must have a public Item indexed property (an indexer in C#) that takes an integer, and it must have a public Count property of type integer. The parameter passed to the Add method must be the same type as that returned from the Item property, or one of that type's bases. For classes implementing ICollection, values to be serialized will be retrieved from the indexed Item property rather than by calling GetEnumerator. Also note that public fields and properties will not be serialized, with the exception of public fields that return another collection class (one that implements ICollection).

使用XML串行化属性(Attributes)(如:XmlArray,XmlArrayItem)来串行化集合类!

串行化包含数组(Arrays)的数据

using System;
using System.Collections;
using System.Xml.Serialization;
 /// <summary>
 /// Summary description for Cars.
 /// </summary>
    [XmlRoot("carsCollection")]
    public class CarsArray {
        private Car[] _CarsList = null;

        public CarsArray() {}    
    
        public CarsArray(int size) {
            _CarsList = new Car[size];
        }

        [XmlArray("carsArray")]
        [XmlArrayItem("car")]
        public Car[] CarsCollection {
            get {
                return _CarsList;
            }
            set {
                _CarsList = value;
            }
        }

        public Car this[int index] {
            get {
                if (index <= _CarsList.GetUpperBound(0) || index > -1)
                    return (Car)_CarsList[index];
                else
                    throw new IndexOutOfRangeException("Invalid index value passed.");
            }
            set {
                if (index <= _CarsList.GetUpperBound(0) || index > -1)
                    _CarsList[index] = value;
                else
                    throw new IndexOutOfRangeException("Invalid index value passed.");

            }
        }

    }
로그인 후 복사

结果为:

<?xml version="1.0" encoding="utf-16"?>
<carsCollection xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <carsArray>
    <car>
      <license>1234</license>
      <color>Black</color>
    </car>
    <car>
      <license>4321</license>
      <color>Blue</color>
    </car>
  </carsArray>
</carsCollection>
로그인 후 복사
  • 串行化ArrayLists

  • using System;
    using System.Collections;
    using System.Xml.Serialization;
    
        /// <summary>
        /// Summary description for Cars.
        /// </summary>
        [XmlRoot("carsCollection")]
        public class CarsArrayList {
            private ArrayList _CarsList = new ArrayList();
    
            public CarsArrayList() {}        
    
            [XmlArray("carsArrayList")]
            [XmlArrayItem("car",typeof(Car))]
            public ArrayList CarsCollection {
                get {
                    return _CarsList;
                }
                set {
                    _CarsList = value;
                }
            }
    
            public Car this[int index] {
                get {
                    return (Car)_CarsList[index];
                }
                set {
                    if (index > _CarsList.Count-1)
                        _CarsList.Add(value);
                    else
                        _CarsList[index] = value;
                }
            }
    
        }
    로그인 후 복사



结果为:

<?xml version="1.0" encoding="utf-16"?>
<carsCollection xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <carsArrayList>
    <car>
      <license>1234</license>
      <color>Black</color>
    </car>
    <car>
      <license>4321</license>
      <color>Blue</color>
    </car>
  </carsArrayList>
</carsCollection>
로그인 후 복사

------------------------------------------------------------------

购买订单示例

例子很简单,也很完整,它使用CreatePO来创建 PurchaseOrder, Address,和 OrderedItem类,并串行化它们.ReadPo实现反串行化.

可以将附加的特性用于类和属性.你必须引用System.Xml.Serialization名字空间来用这些特性.

特性用途
[XmlIgnore]当公有的属性或字段不包括在串行化的XML结构中时。
[XmlRoot]用来识别作为XML文件根元素的类或结构。你可以用它来把一个元素名设置为根元素。
[XmlElement]当公有的属性或字段可以作为一个元素被串行化到XML结构中时。
[XmlAttribute]当公有的属性或字段可以作为一个特性被串行化到XML结构中时。
[XmlArray]当公有的属性或字段可以作为一个元素数组被串行化到XML结构中时。当一组对象用在一个类中时,这个特性很有用。
[XmlArrayItem]用来识别可以放到一个串行化数组中的类型。



再次提醒大家注意,只能串行化公共(public)类和公共(public)字段(fields)和性质(property).

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
// The XmlRootAttribute allows you to set an alternate name 
// (PurchaseOrder) for the XML element and its 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)
    {
        // Creates an instance of the XmlSerializer class;
        // specifies the type of object to serialize.
        XmlSerializer serializer = 
        new XmlSerializer(typeof(PurchaseOrder));
        TextWriter writer = new StreamWriter(filename);
        PurchaseOrder po=new PurchaseOrder();
         
        // Creates 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";
        // Sets ShipTo and BillTo to the same addressee.
        po.ShipTo = billAddress;
        po.OrderDate = System.DateTime.Now.ToLongDateString();
    
        // Creates an OrderedItem.
        OrderedItem i1 = new OrderedItem();
        i1.ItemName = "Widget S";
        i1.Description = "Small widget";
        i1.UnitPrice = (decimal) 5.23;
        i1.Quantity = 3;
        i1.Calculate();
    
        // Inserts 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; 
        // Serializes the purchase order, and closes the TextWriter.
        serializer.Serialize(writer, po);
        writer.Close();
    }
    
    protected void ReadPO(string filename)
    {
        // Creates an instance of the XmlSerializer class;
        // specifies 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, handles them with the 
        // UnknownNode and UnknownAttribute events.
        //在并行的xml当中可能存在意外的xml节点,如果不处理这些意外的xml 的节
        //点,XmlSerializer将忽略这些意外的节点,如果要处理这些意外节点,可以使用
        //XmlSerializer的一下事件进行处理:UnknownNode,UnknownElement  ,
        //UnknownAttribute ,UnreferencedObject
        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);
        // Declares an object variable of the type to be deserialized.
        PurchaseOrder po;
        // Uses the Deserialize method to restore the object&#39;s state with
        // data from the XML document. */
        po = (PurchaseOrder) serializer.Deserialize(fs);
        // Reads the order date.
        Console.WriteLine ("OrderDate: " + po.OrderDate);
    
        // Reads the shipping address.
        Address shipTo = po.ShipTo;
        ReadAddress(shipTo, "Ship To:");
        // Reads 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);
        }
        // Reads the subtotal, shipping cost, and total cost.
        Console.WriteLine(
        "\n\t\t\t\t\t Subtotal\t" + po.SubTotal + 
        "\n\t\t\t\t\t Shipping\t" + po.ShipCost + 
        "\n\t\t\t\t\t Total\t\t" + po.TotalCost
        );
    }
    
    protected void ReadAddress(Address a, string label)
    {
        // Reads the fields of the Address.
        Console.WriteLine(label);
        Console.Write("\t"+
        a.Name +"\n\t" +
        a.Line1 +"\n\t" +
        a.City +"\t" +
        a.State +"\n\t" +
        a.Zip +"\n");
    }
    protected void serializer_UnknownNode
    (object sender, XmlNodeEventArgs e)
    {
        Console.WriteLine("Unknown Node:" +   e.Name + "\t" + e.Text);
    }
    protected void serializer_UnknownAttribute
    (object sender, XmlAttributeEventArgs e)
    {
        System.Xml.XmlAttribute attr = e.Attr;
        Console.WriteLine("Unknown attribute " + 
        attr.Name + "=&#39;" + attr.Value + "&#39;");
    }
}
로그인 후 복사

xml输出如下:

<?xml version="1.0" encoding="utf-8"?>
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.cpandl.com">
    <ShipTo Name="Teresa Atkinson">
        <Line1>1 Main St.</Line1>
        <City>AnyTown</City>
        <State>WA</State>
        <Zip>00000</Zip>
    </ShipTo>
    <OrderDate>Wednesday, June 27, 2001</OrderDate>
    <Items>
        <OrderedItem>
            <ItemName>Widget S</ItemName>
            <Description>Small widget</Description>
            <UnitPrice>5.23</UnitPrice>
            <Quantity>3</Quantity>
            <LineTotal>15.69</LineTotal>
        </OrderedItem>
    </Items>
    <SubTotal>15.69</SubTotal>
    <ShipCost>12.51</ShipCost>
    <TotalCost>28.2</TotalCost>
</PurchaseOrder>
로그인 후 복사


위 내용은 XML 직렬화 샘플 코드 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PowerPoint를 사용하여 XML 파일을 열 수 있나요? PowerPoint를 사용하여 XML 파일을 열 수 있나요? Feb 19, 2024 pm 09:06 PM

XML 파일을 PPT로 열 수 있나요? XML, Extensible Markup Language(Extensible Markup Language)는 데이터 교환 및 데이터 저장에 널리 사용되는 범용 마크업 언어입니다. HTML에 비해 XML은 더 유연하고 자체 태그와 데이터 구조를 정의할 수 있으므로 데이터 저장과 교환이 더 편리하고 통합됩니다. PPT 또는 PowerPoint는 프레젠테이션 작성을 위해 Microsoft에서 개발한 소프트웨어입니다. 이는 포괄적인 방법을 제공합니다.

Python을 사용하여 XML 데이터 병합 및 중복 제거 Python을 사용하여 XML 데이터 병합 및 중복 제거 Aug 07, 2023 am 11:33 AM

Python을 사용하여 XML 데이터 병합 및 중복 제거 XML(eXtensibleMarkupLanguage)은 데이터를 저장하고 전송하는 데 사용되는 마크업 언어입니다. XML 데이터를 처리할 때 여러 XML 파일을 하나로 병합하거나 중복된 데이터를 제거해야 하는 경우가 있습니다. 이 기사에서는 Python을 사용하여 XML 데이터 병합 및 중복 제거를 구현하는 방법을 소개하고 해당 코드 예제를 제공합니다. 1. XML 데이터 병합 XML 파일이 여러 개인 경우 이를 병합해야 합니다.

Python에서 XML 데이터를 CSV 형식으로 변환 Python에서 XML 데이터를 CSV 형식으로 변환 Aug 11, 2023 pm 07:41 PM

Python의 XML 데이터를 CSV 형식으로 변환 XML(ExtensibleMarkupLanguage)은 데이터 저장 및 전송에 일반적으로 사용되는 확장 가능한 마크업 언어입니다. CSV(CommaSeparatedValues)는 데이터 가져오기 및 내보내기에 일반적으로 사용되는 쉼표로 구분된 텍스트 파일 형식입니다. 데이터를 처리할 때, 간편한 분석과 처리를 위해 XML 데이터를 CSV 형식으로 변환해야 하는 경우가 있습니다. 파이썬은 강력하다

Python을 사용하여 XML 데이터 필터링 및 정렬 Python을 사용하여 XML 데이터 필터링 및 정렬 Aug 07, 2023 pm 04:17 PM

Python을 사용하여 XML 데이터 필터링 및 정렬 구현 소개: XML은 데이터를 태그 및 속성 형식으로 저장하는 일반적으로 사용되는 데이터 교환 형식입니다. XML 데이터를 처리할 때 데이터를 필터링하고 정렬해야 하는 경우가 많습니다. Python은 XML 데이터를 처리하는 데 유용한 많은 도구와 라이브러리를 제공합니다. 이 기사에서는 Python을 사용하여 XML 데이터를 필터링하고 정렬하는 방법을 소개합니다. XML 파일 읽기 시작하기 전에 XML 파일을 읽어야 합니다. Python에는 많은 XML 처리 라이브러리가 있습니다.

PHP를 사용하여 XML 데이터를 데이터베이스로 가져오기 PHP를 사용하여 XML 데이터를 데이터베이스로 가져오기 Aug 07, 2023 am 09:58 AM

PHP를 사용하여 데이터베이스로 XML 데이터 가져오기 소개: 개발 중에 추가 처리 및 분석을 위해 외부 데이터를 데이터베이스로 가져와야 하는 경우가 많습니다. 일반적으로 사용되는 데이터 교환 형식인 XML은 구조화된 데이터를 저장하고 전송하는 데 자주 사용됩니다. 이 기사에서는 PHP를 사용하여 XML 데이터를 데이터베이스로 가져오는 방법을 소개합니다. 1단계: XML 파일 구문 분석 먼저 XML 파일을 구문 분석하고 필요한 데이터를 추출해야 합니다. PHP는 XML을 구문 분석하는 여러 가지 방법을 제공하며 그 중 가장 일반적으로 사용되는 방법은 Simple을 사용하는 것입니다.

Python은 XML과 JSON 간의 변환을 구현합니다. Python은 XML과 JSON 간의 변환을 구현합니다. Aug 07, 2023 pm 07:10 PM

Python은 XML과 JSON 간의 변환을 구현합니다. 소개: 일상적인 개발 프로세스에서 우리는 종종 서로 다른 형식 간에 데이터를 변환해야 합니다. XML과 JSON은 일반적인 데이터 교환 형식입니다. Python에서는 다양한 라이브러리를 사용하여 XML과 JSON을 변환할 수 있습니다. 이 문서에서는 코드 예제와 함께 일반적으로 사용되는 몇 가지 방법을 소개합니다. 1. Python에서 XML을 JSON으로 변환하려면 xml.etree.ElementTree 모듈을 사용할 수 있습니다.

Python을 사용하여 XML의 오류 및 예외 처리 Python을 사용하여 XML의 오류 및 예외 처리 Aug 08, 2023 pm 12:25 PM

Python을 사용하여 XML에서 오류 및 예외 처리하기 XML은 구조화된 데이터를 저장하고 표현하는 데 일반적으로 사용되는 데이터 형식입니다. Python을 사용하여 XML을 처리할 때 때때로 오류와 예외가 발생할 수 있습니다. 이 기사에서는 Python을 사용하여 XML의 오류 및 예외를 처리하는 방법을 소개하고 참조용 샘플 코드를 제공합니다. XML 구문 분석 오류를 잡기 위해 try-Exception 문을 사용하십시오. Python을 사용하여 XML을 구문 분석할 때 가끔 오류가 발생할 수 있습니다.

Python은 XML의 특수 문자와 이스케이프 시퀀스를 구문 분석합니다. Python은 XML의 특수 문자와 이스케이프 시퀀스를 구문 분석합니다. Aug 08, 2023 pm 12:46 PM

Python은 XML의 특수 문자와 이스케이프 시퀀스를 구문 분석합니다. XML(eXtensibleMarkupLanguage)은 서로 다른 시스템 간에 데이터를 전송하고 저장하는 데 일반적으로 사용되는 데이터 교환 형식입니다. XML 파일을 처리할 때 특수 문자와 이스케이프 시퀀스가 ​​포함되어 구문 분석 오류가 발생하거나 데이터가 잘못 해석될 수 있는 상황이 자주 발생합니다. 따라서 Python을 사용하여 XML 파일을 구문 분석할 때 이러한 특수 문자와 이스케이프 시퀀스를 처리하는 방법을 이해해야 합니다. 1. 특수문자 및

See all articles