用 Serialization 將物件存成XML

  • 889
  • 0

當我們要將物件直接轉成xml格式資料

步驟

  1. 先確認要產生的XML檔案格式
  2. 建立XML檔案格式對應的類別屬性
  3. 建立物件並取得資料
  4. 用 XmlSerializer 將物件轉成XML格式並存檔

實例

  1. 要產生的XML檔案格式
    <?xml version="1.0"?>
    <ORDER_DOC xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <ORDER>
        <ECNO>102</ECNO>
        <ODNO>00000000001</ODNO>
        <STNO>F001234</STNO>
        <AMT>500</AMT>
        <CUTKNM><![CDATA[劉德華]]></CUTKNM>
      </ORDER>
      <ORDER>
        <ECNO>102</ECNO>
        <ODNO>00000000002</ODNO>
        <STNO>F001235</STNO>
        <AMT>400</AMT>
        <CUTKNM><![CDATA[張學友]]></CUTKNM>
      </ORDER>
      <ORDERCOUNT>
        <TOTALS>2</TOTALS>
      </ORDERCOUNT>
    </ORDER_DOC>

     

  2. 建立XML檔案格式對應的類別屬性
     

    namespace Models
    {
        using System.Xml;
        using System.Xml.Serialization;
    
        [Serializable]
        [XmlType("ORDER")]
        public class F10Model 
        {
            private string _cutknm;
    
            [XmlElement(ElementName = "ECNO")]
            public string ECNO { get; set; }
    
            [XmlElement(ElementName = "ODNO")]
            public string ODNO { get; set; }
    
            [XmlElement(ElementName = "STNO")]
            public string STNO { get; set; }
    
            [XmlElement(ElementName = "AMT")]
            public string AMT { get; set; }
    
            [XmlElement(ElementName = "CUTKNM")]
            public string CUTKNM
            {
                get
                {
                    XmlDocument xDoc = new XmlDocument();
                    return xDoc.CreateCDataSection(this._cutknm).OuterXml;
                }
                set
                {
                    this._cutknm = value;
                }
            }
        }
    }

     

  3. 建立物件並取得資料
     

                List<Models.F10Model> F10ModelList = new List<Models.F10Model>();
                F10ModelList.Add(new Models.F10Model()
                {
                    ECNO = "102",
                    ODNO = "00000000001",
                    STNO = "F001234",
                    AMT = "500",
                    CUTKNM = "劉德華"
                });
                F10ModelList.Add(new Models.F10Model()
                {
                    ECNO = "102",
                    ODNO = "00000000002",
                    STNO = "F001235",
                    AMT = "400",
                    CUTKNM = "張學友"
                });

     

  4. 用 XmlSerializer 將物件轉成XML格式並存檔
     

                // 將物件轉換成XML檔案
                XmlSerializer xs = new XmlSerializer(typeof(List<F10Model>),
                    new XmlRootAttribute() { ElementName = "ORDER_DOC" });
                using (FileStream fs = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
                {
                    xs.Serialize(fs, f10ModelList);
                }
    
                // 將檔案取出作必要的調整
                string xml;
                using (StreamReader sr = new StreamReader(tempFilePath, Encoding.UTF8))
                {
                    xml = sr.ReadToEnd();
                    // 設定插入訂單數量的element
                    string orderCountBlock = string.Format("  <ORDERCOUNT>\r\n    <TOTALS>{0}</TOTALS>\r\n  </ORDERCOUNT>\r\n</ORDER_DOC>", f10ModelList.Count);
                    // 插入訂單數量的element
                    xml = xml.Replace("</ORDER_DOC>", orderCountBlock);
                    // 轉換特殊字符
                    xml = xml.Replace("&lt;", "<");
                    xml = xml.Replace("&gt;", ">");
                    xml = xml.Replace("&amp;", "&");
                    xml = xml.Replace("&apos;", "'");
                    xml = xml.Replace("&quot;", "\"");
                }
                // 資料再寫入檔案
                File.WriteAllText(tempFilePath, xml);