记一次解析XML转对象的笔记

时间:2024-01-18 13:09:32

项目中调用第三方API,返回格式是XML字符串,需要将XML反序列化为对象,格式如下:

 <?xml version="1.0"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" totalCount="" resultCode="ABC" resultMessage="测试">
<profile lastName="李" firstName="爽" dateOfBirth="XX0816" age="" gender="" address="浙江省 杭州富阳市 东州工业园区3号路1号杭州龙盛工贸有限公" email="htlslll@163.com" cellEmail="" socialMedia="" homePhone="" cellPhone="" contactabiltyMail="" contactabiltyEmail="" contactabiltyCellEmail="" contactabiltyHomePhone="" contactabiltyCellPhone="" contactabiltyText="" contactabiltySocialMedia="" vipLevel="" memberId="OC540C00016824" saAccount="" classa="小姐" homeStoreCode="OC54" />
<purchaseHistory>
<departmentPurchase totalLifeTimeSale="" totalTYAmount="" lastTxn="" totalTYUnitCnt="" firstTxn="">
<department categoryName="D08" tyAmount="" tyUnitCnt="" />
<department categoryName="D01" tyAmount="" tyUnitCnt="" />
<department categoryName="D02" tyAmount="" tyUnitCnt="" />
</departmentPurchase>
<ratePurchase totalLyAmount="" totalLyRate="" totalTyAmount="" totalTyRate="" totalLifeTimeAmount="" totalLifeTimeRate="">
<rate categoryName="Retail" lyAmount="" lyRate="" lyToDate="" tyAmount="" tyRate="" tyToDate="" lifeTimeAmount="" lifeTimeRate="" lyTyChange="" />
</ratePurchase>
<storeRatePurchase>
<storeRate />
</storeRatePurchase>
</purchaseHistory>
<vipStatus issueDate="" issueShop="OC54" ptsToUpgrade="" expiryDate="" upgradeShop="" ptsToRenew="" />
<comments comment="第一场雪" />
</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
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string totalCount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string resultCode { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string resultMessage { get; set; } [System.Xml.Serialization.XmlElementAttribute("profile", typeof(profile))]
public profile profile { get; set; } [System.Xml.Serialization.XmlElementAttribute("purchaseHistory", typeof(purchaseHistory))]
public purchaseHistory purchaseHistory { get; set; } [System.Xml.Serialization.XmlElementAttribute("vipStatus", typeof(vipStatus))]
public vipStatus vipStatus { get; set; } [System.Xml.Serialization.XmlElementAttribute("comments", typeof(comments))]
public comments comments { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class profile
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string lastName { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string firstName { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string dateOfBirth { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string age { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string gender { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string address { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string email { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string cellEmail { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string socialMedia { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string homePhone { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string cellPhone { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string contactabiltyMail { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string contactabiltyEmail { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string contactabiltyCellEmail { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string contactabiltyHomePhone { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string contactabiltyCellPhone { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string contactabiltyText { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string contactabiltySocialMedia { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string vipLevel { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string memberId { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string saAccount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string classa { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string homeStoreCode { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class purchaseHistory
{ [System.Xml.Serialization.XmlElementAttribute("departmentPurchase", typeof(departmentPurchase))]
public departmentPurchase departmentPurchase { get; set; } [System.Xml.Serialization.XmlElementAttribute("ratePurchase", typeof(ratePurchase))]
public ratePurchase ratePurchase { get; set; } [System.Xml.Serialization.XmlElementAttribute("storeRatePurchase", typeof(storeRatePurchase))]
public storeRatePurchase storeRatePurchase { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class departmentPurchase
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string totalTYAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalTYUnitCnt { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string firstTxn { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lastTxn { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalLifeTimeSale { get; set; } [System.Xml.Serialization.XmlElementAttribute("department", typeof(List<department>), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = )]
public List<department> department { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class department
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string categoryName { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string tyAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string tyUnitCnt { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class ratePurchase
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string totalLyAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalLyRate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalTyAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalTyRate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalLifeTimeAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalLifeTimeRate { get; set; } [System.Xml.Serialization.XmlElementAttribute("rate", typeof(rate))]
public rate rate { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class rate
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string categoryName { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lyAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lyRate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lyToDate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string tyAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string tyRate { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()] public string tyToDate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lifeTimeAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lifeTimeRate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lyTyChange { get; set; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class storeRatePurchase
{
public string storeRate { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class vipStatus
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string issueDate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string issueShop { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string ptsToUpgrade { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string expiryDate { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string upgradeShop { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string ptsToRenew { get; set; }
} [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class comments
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string comment { get; set; }
}

解析代码如下

   private static System.Xml.Serialization.XmlSerializer Serializer;
/// <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
{
Serializer = Serializer ?? new XmlSerializer(typeof(T));
stringReader = new StringReader(xml);
T result = Serializer.Deserialize(stringReader) as T;
return result;
}
finally
{
if ((stringReader != null))
{
stringReader.Dispose();
}
}
}

调用方式:

var rpXML = AcxiomXMLHelper.DeserializeForXml<CustomerDetails.Response>(returnXML);

好了,接下来就出现了问题

departmentPurchase 下面的department始终是没有数据,调试好久都找不到问题出现在哪里。

尝试找解决的办法,先实例化一个Response对象序列化后写入文件,再将文件内容读出来反序列化出来

 Response response = new Response
{
totalCount = "",
resultCode = "ABC",
resultMessage = "测试",
profile = new profile { lastName = "李", firstName = "爽", dateOfBirth = "XX0816", age = "", gender = "", address = "浙江省 杭州富阳市 东州工业园区3号路1号杭州龙盛工贸有限公", email = "htlslll@163.com", cellEmail = "", socialMedia = "", homePhone = "", cellPhone = "", contactabiltyMail = "", contactabiltyEmail = "", contactabiltyCellEmail = "", contactabiltyHomePhone = "", contactabiltyCellPhone = "", contactabiltyText = "", contactabiltySocialMedia = "", vipLevel = "", memberId = "OC540C00016824", saAccount = "", classa = "小姐", homeStoreCode = "OC54" },
comments = new comments { comment = "第一场雪" },
purchaseHistory = new purchaseHistory
{
departmentPurchase = new departmentPurchase
{
totalTYAmount = "",
totalTYUnitCnt = "",
firstTxn = "",
lastTxn = "",
totalLifeTimeSale = "",
department = new List<department> {
new department { categoryName = "D08", tyAmount = "", tyUnitCnt = "" },
new department { categoryName = "D01", tyAmount = "", tyUnitCnt = "" },
new department { categoryName = "D02", tyAmount = "", tyUnitCnt = "" }
}
},
ratePurchase = new ratePurchase
{
totalLyAmount = "",
totalLyRate = "",
totalTyAmount = "",
totalTyRate = "",
totalLifeTimeAmount = "",
totalLifeTimeRate = "",
rate = new rate { categoryName = "Retail", lyAmount = "", lyRate = "", lyToDate = "", tyAmount = "", tyRate = "", tyToDate = "", lifeTimeAmount = "", lifeTimeRate = "", lyTyChange = "" }
},
storeRatePurchase = new storeRatePurchase { storeRate = string.Empty }
},
vipStatus = new vipStatus { issueDate = "", issueShop = "OC54", ptsToUpgrade = "", expiryDate = "", upgradeShop = "", ptsToRenew = "" }
}; FileStream stream = new FileStream(@"d:\xmlFormat.xml", FileMode.Create);
XmlSerializer xmlserilize = new XmlSerializer(typeof(Response));
xmlserilize.Serialize(stream, response); stream.Close(); using (FileStream xmlStream = new FileStream(@"d:\xmlFormat.xml", FileMode.Open))
{
using (XmlReader xmlReader = XmlReader.Create(xmlStream))
{
XmlSerializer serializer = new XmlSerializer(typeof(Response));
Response res = serializer.Deserialize(xmlReader) as Response;
}
}

代码中res是反序列化的结果,数据都正确。这就有点恼火了,怎么办呢?

比较我生成的文件和API返回的XML:

下面是我生成的XML格式

 <Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" totalCount="" resultCode="ABC" resultMessage="测试">
<profile lastName="李" firstName="爽" dateOfBirth="XX0816" age="" gender="" address="浙江省 杭州富阳市 东州工业园区3号路1号杭州龙盛工贸有限公" email="htlslll@163.com" cellEmail="" socialMedia="" homePhone="" cellPhone="" contactabiltyMail="" contactabiltyEmail="" contactabiltyCellEmail="" contactabiltyHomePhone="" contactabiltyCellPhone="" contactabiltyText="" contactabiltySocialMedia="" vipLevel="" memberId="OC540C00016824" saAccount="" classa="小姐" homeStoreCode="OC54" />
<purchaseHistory>
<departmentPurchase totalLifeTimeSale="" totalTYAmount="" lastTxn="" totalTYUnitCnt="" firstTxn="">
<department>
<department categoryName="D08" tyAmount="" tyUnitCnt="" />
<department categoryName="D01" tyAmount="" tyUnitCnt="" />
<department categoryName="D02" tyAmount="" tyUnitCnt="" />
</department>
</departmentPurchase>
<ratePurchase totalLyAmount="" totalLyRate="" totalTyAmount="" totalTyRate="" totalLifeTimeAmount="" totalLifeTimeRate="">
<rate categoryName="Retail" lyAmount="" lyRate="" lyToDate="" tyAmount="" tyRate="" tyToDate="" lifeTimeAmount="" lifeTimeRate="" lyTyChange="" />
</ratePurchase>
<storeRatePurchase>
<storeRate />
</storeRatePurchase>
</purchaseHistory>
<vipStatus issueDate="" issueShop="OC54" ptsToUpgrade="" expiryDate="" upgradeShop="" ptsToRenew="" />
<comments comment="第一场雪" />
</Response>

仔细比对发现问题

在departmentPurchase 节点下我多了一层department节点,可我是按照接口的结果定义的对象啊

   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34209")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class departmentPurchase
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public string totalTYAmount { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalTYUnitCnt { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string firstTxn { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string lastTxn { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()]
public string totalLifeTimeSale { get; set; } [System.Xml.Serialization.XmlElementAttribute("department", typeof(List<department>), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = )]
public List<department> department { get; set; }
}

怎么搞呢?在网上不停的找答案,最终都无解。但是没有放弃,答案也往往在快要放弃的时候出现

我尝试的修改了department的定义

修改前

 [System.Xml.Serialization.XmlElementAttribute("department", typeof(List<department>), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = )]
public List<department> department { get; set; }

修改后

 [System.Xml.Serialization.XmlElementAttribute("department", typeof(department), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = )]
public List<department> department { get; set; }

重新运行,奇迹出现

 <?xml version="1.0"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" totalCount="" resultCode="ABC" resultMessage="测试">
<profile lastName="李" firstName="爽" dateOfBirth="XX0816" age="" gender="" address="浙江省 杭州富阳市 东州工业园区3号路1号杭州龙盛工贸有限公" email="htlslll@163.com" cellEmail="" socialMedia="" homePhone="" cellPhone="" contactabiltyMail="" contactabiltyEmail="" contactabiltyCellEmail="" contactabiltyHomePhone="" contactabiltyCellPhone="" contactabiltyText="" contactabiltySocialMedia="" vipLevel="" memberId="OC540C00016824" saAccount="" classa="小姐" homeStoreCode="OC54" />
<purchaseHistory>
<departmentPurchase totalLifeTimeSale="" totalTYAmount="" lastTxn="" totalTYUnitCnt="" firstTxn="">
<department categoryName="D08" tyAmount="" tyUnitCnt="" />
<department categoryName="D01" tyAmount="" tyUnitCnt="" />
<department categoryName="D02" tyAmount="" tyUnitCnt="" />
</departmentPurchase>
<ratePurchase totalLyAmount="" totalLyRate="" totalTyAmount="" totalTyRate="" totalLifeTimeAmount="" totalLifeTimeRate="">
<rate categoryName="Retail" lyAmount="" lyRate="" lyToDate="" tyAmount="" tyRate="" tyToDate="" lifeTimeAmount="" lifeTimeRate="" lyTyChange="" />
</ratePurchase>
<storeRatePurchase>
<storeRate />
</storeRatePurchase>
</purchaseHistory>
<vipStatus issueDate="" issueShop="OC54" ptsToUpgrade="" expiryDate="" upgradeShop="" ptsToRenew="" />
<comments comment="第一场雪" />
</Response>

问题解决。

原因就出在解析XML节点的

typeof(department) 与 typeof(List<department>)