我正在使用第 3 方 XML API,并已將來自 API 的郵遞員回應和結果中的“Pasted XML As Classes”復制到 Visual Studio 中。這給了我一個具有以下屬性的物件:
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class forum : ItemBase
{
private forumThread[] threadsField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("thread", IsNullable = false)]
public forumThread[] threads
{
get
{
return this.threadsField;
}
set
{
this.threadsField = value;
}
}
}
這可以很好地反序列化并捕獲所有資料。但是,我想稍微清理一下生成的代碼,例如,我想重命名屬性名稱以及forumList遵循 C# PascalCase 約定的類。所以我想重命名threads為Threads和。對于其他屬性/屬性,我通過向屬性添加名稱成功地做到了這一點,但在這種情況下,當我將生成的代碼更改為此時,這不起作用,例如:forumThreadForumThread
[XmlArrayItem("thread", ElementName = "threads", IsNullable = false)]
public forumThread[] Threads {get; set;}
它每次都反序列化為 null 并從 API 呼叫中丟失資料。對此的任何幫助將不勝感激。
反序列化物件的類在這里:
public T Deserialize<T>(string xml)
where T : ItemBase
{
if (string.IsNullOrWhiteSpace(xml))
{
return null;
}
using var stringReader = new StringReader(xml);
var serializer = new XmlSerializer(typeof(T));
var xmlReader = new XmlTextReader(stringReader);
return (T)serializer.Deserialize(xmlReader);
}
以及我們正在反序列化的 xml 示例:
<forum id="3" title="Testing Forum" numthreads="1816" numposts="13685" lastpostdate="Thu, 01 Jan 1970 00:00:00 0000" noposting="0" termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
<threads>
<thread id="568813" subject="test thread" author="dakarp" numarticles="16" postdate="Tue, 28 Sep 2010 05:59:08 0000" lastpostdate="Sat, 02 Apr 2022 11:57:08 0000" />
<thread id="1848343" subject="Test" author="Grafin" numarticles="1195" postdate="Thu, 14 Sep 2017 05:14:46 0000" lastpostdate="Sun, 15 May 2022 13:39:34 0000" />
</threads>
</forum>
uj5u.com熱心網友回復:
以下解決了該問題,并且似乎是使其正確反序列化所需的屬性。我不太清楚生成的代碼做了什么來達到相同的結果,但這鞏固了我對 JSON 的偏好而不是 xml
[XmlArray("threads")]
[XmlArrayItem("thread")]
public forumThread[] Threads { get; set; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478394.html
上一篇:XML:洗掉標簽但保留文本
