我有這樣一段XML(實際上是XBRL,但那是基于XML的)
。<xbrl>
<context id="Context_Duration" />
<context id="Context_Instant_Begin"/span> />
<context id="Context_Instant_End"/span> />
<ConstructionDepotSpecification>
<ConstructionDepotLabel contextRef="Context_Duration"/span>> depot</ConstructionDepotLabel>。
<ConstructionDepotBalance contextRef="Context_Instant_Begin"/span>> 45000</ConstructionDepotBalance>。
<ConstructionDepotBalance contextRef="Context_Instant_End"/span>> 42000</ConstructionDepotBalance>。
</ConstructionDepotSpecification>/span>
</xbrl>/span>
(為清晰起見,洗掉了額外的內容和xml命名空間的宣告)
我想將其反序列化為一個類,但是我不確定如何處理ConstructionDepotBalance元素。如果我定義一個屬性ConstructionDepotBalance,它將只取第一個元素的值,所以我想我應該創建兩個屬性,一個是開始值,一個是結束值。 所以這個類應該是這樣的
。[XmlRoot(ElementName = "xbrl"/span>)]
public partial class Taxonomy
{
[XmlElement ]
public List<ConstructionDepotSpecification> ConstructionDepotSpecification { get; set; }
}
public partial class ConstructionDepotSpecificationpublic string ConstructionDepotLabel { get; set; }
public long? ConstructionDepotBalanceBegin { get; set; }
public long? ConstructionDepotBalanceEnd { get; set; }
因此,帶有屬性Context_Instant_Begin的元素應該被反序列化為ConstructionDepotBalanceBegin,另一個帶有屬性Context_Instant_End的元素應該被反序列化為ConstructionDepotBalanceEnd。
這有可能實作嗎?我是否應該為此使用IXmlSerializable的實作呢?
uj5u.com熱心網友回復:
我的第一個方法是:
你可以先決議XML-String,然后替換
你可以先決議XML-String,然后替換
[ConstructionDepotBalance contextRef="Context_Instant_Begin"]
與
[ConstructionDepotBalanceBegin]
(與ConstructionDepotBalanceEnd相同)。
在第二步中,你對XML字串進行反序列化。
uj5u.com熱心網友回復:
我對IXmlSerializable介面進行了一些實驗,并得出了這樣的實作:
我對IXmlSerializable介面進行了一些實驗。
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement()。
while (! reader.EOF)
{
var ctx = reader.GetAttribute("contextRef") 。
if (ctx == "Context_Duration")
{
string propName = reader.Name。
var propInfo = GetType().GetProperty(propName);
Type propType = propInfo.PropertyType。
if (propType.GenericTypeArguments.Length > 0)
{
propType = propType.GenericTypeArguments[0] 。
}
var value = reader.ReadElementContentAs(propType, null)。
propInfo.SetValue(this, value)。
}
else if (ctx == "Context_Instant_Begin"/span>)
{
string propName = reader.Name "Begin" ;
var propInfo = GetType().GetProperty(propName);
var value = reader.ReadElementContentAsLong()。
propInfo.SetValue(this, value)。
}
else if (ctx == "Context_Instant_End")
{
string propName = reader.Name "End" ;
var propInfo = GetType().GetProperty(propName);
var value = reader.ReadElementContentAsLong()。
propInfo.SetValue(this, value)。
}
if (reader.NodeType == XmlNodeType.EndElement)
{
reader.ReadEndElement()。
break;
}
}
}
不確定這是否是這個問題的最佳解決方案,但目前它能滿足我的要求。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/324053.html
標籤:
