XML轉成對象走過的坑

不想多說,一言不合上代碼:

待轉換的XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response totalCount="1" resultCode="SUCCESS" resultMessage="">
    <profile lastName="李" firstName="*" dateOfBirth="XX0816" age="" gender="1" address="浙江省 杭州富陽市 東州貿有限公" email="[email protected]" cellEmail="" socialMedia="" homePhone="" cellPhone="199925" contactabiltyMail="1" contactabiltyEmail="1" contactabiltyCellEmail="0" contactabiltyHomePhone="1" contactabiltyCellPhone="1" contactabiltyText="1" contactabiltySocialMedia="0" vipLevel="2" memberId="OC540C00016824" saAccount="660996" class="小姐" homeStoreCode="OC54"/>
    <purchaseHistory>
        <departmentPurchase totalTYAmount="21705" totalTYUnitCnt="9" firstTxn="20160713" lastTxn="20160829" totalLifeTimeSale="36791">
            <department categoryName="D02" tyAmount="8985" tyUnitCnt="4"/>
            <department categoryName="D08" tyAmount="2970" tyUnitCnt="2"/>
            <department categoryName="D01" tyAmount="9750" tyUnitCnt="3"/>
        </departmentPurchase>
        <ratePurchase totalLyAmount="0" totalLyRate="0" totalTyAmount="21705" totalTyRate="100" totalLifeTimeAmount="36791" totalLifeTimeRate="100">
            <rate categoryName="Retail" lyAmount="" lyRate="0" lyToDate="0" tyAmount="21705" tyRate="100" tyToDate="21705" lifeTimeAmount="36791" lifeTimeRate="100" lyTyChange="100"/>
        </ratePurchase>
        <storeRatePurchase>
            <storeRate/>
        </storeRatePurchase>
    </purchaseHistory>
    <vipStatus issueDate="20140629" issueShop="OC54" ptsToUpgrade="21705" expiryDate="20170731" upgradeShop="" ptsToRenew="8130"/>
    <comments comment=""/>
</response>
轉換方法:

  /// <summary>
        /// 指定XML字符串序列化成對象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeForXml<T>(string xml) where T : class, new()
        {
            System.IO.StringReader stringReader = null;
            try
            {               
                if ((Serializer == null))
                {
                    Serializer = new XmlSerializer(typeof(T));
                }

                stringReader = new StringReader(xml);
                T result = Serializer.Deserialize(stringReader) as T;
                return result;
            }
            finally
            {
                if ((stringReader != null))
                {
                    stringReader.Dispose();
                }
            }
        }
調用方法:

rpXML = XMLHelper.DeserializeForXml<CustomerDetails.Response>(returnXML);
T:Response

  /// <summary>
            /// 返回結果(根節點)
            /// </summary>
            [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
            [System.SerializableAttribute()]
            [System.ComponentModel.DesignerCategoryAttribute("code")]
            [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false, ElementName = "response")]
            public class Response
            {
                /// <summary>
                /// 
                /// </summary>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string resultCode { set; get; }

                /// <summary>
                /// 
                /// </summary>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string resultMessage { set; get; }

                /// <summary>
                /// 
                /// </summary>
                [System.Xml.Serialization.XmlElementAttribute("profile", typeof(Profile))]
                public Profile profile { set; get; }
              
                        /// <summary>
                /// 
                /// </summary>
                [System.Xml.Serialization.XmlElement("department", typeof(Department), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
                public List<Department> department { get; set; }
}
特別注意,如果XML節點有對應的List對象,那麼typeof(Department)一定要這麼寫,不能是其他的!




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章