[英]How do I deserialize this XML
How correctly to deserialize XML from my example (look the question in the end)? 如何从我的示例中正确反序列化XML(最后看问题)? Am I doing this right?
我这样做对吗? Maybe there is a way to make it easier and more efficient?
也许有一种方法可以使它更容易,更有效?
XML: XML:
<Warehouse>
<GUID>0d63057d-99e8-11e6-813b-0003ff000011</GUID>
<Name>WarehouseName</Name>
<Terms>
<Term TargetGUID="490ecabf-f011-11e3-b7d9-6c626dc1e098">2</Term>
<Term TargetGUID="f332d7ff-efd2-11e3-b7d9-6c626dc1e098">4</Term>
</Terms>
</Warehouse>
C#: Warehouse.cs: C#:Warehouse.cs:
[Serializable]
public class Warehouse
{
[XmlArray("Terms", IsNullable=true)]
[XmlArrayItem("Term")]
public WarehouseTransferTerm[] TransferTerms { get; set; }
[XmlElement(ElementName="Name")]
public string InternalName { get; set; }
[XmlElement(ElementName="Guid")]
public Guid Guid { get; set; }
}
WarehouseTransferTerm.cs: WarehouseTransferTerm.cs:
[Serializable]
public class WarehouseTransferTerm
{
public Guid SourceWarehouseGuid { get; set; }
[XmlAttribute(AttributeName = "TargetGUID")]
public Guid TargetWarehouseGuid { get; set; }
[XmlElement(ElementName="Term")]
public int TransferTermInDays { get; set; }
}
Question: How I can set Warehouse's GUID property value as SourceWarehouseGuid? 问题:如何将Warehouse的GUID属性值设置为SourceWarehouseGuid?
You could implement custom deserialization logic and just set the value on the dependent items. 您可以实现自定义反序列化逻辑,只需在相关项上设置值。 See here: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.ondeserializedattribute?view=netframework-4.7.2
参见此处: https : //docs.microsoft.com/zh-cn/dotnet/api/system.runtime.serialization.ondeserializedattribute?view=netframework-4.7.2
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{
foreach(var term in TransferTerms)
{
term.TargetWarehouseGuid = this.Guid;
}
}
I like using Dictionaries along with Xml Linq : 我喜欢将字典和Xml Linq一起使用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, XElement> warehouses = doc.Descendants("Warehouse")
.GroupBy(x => (string)x.Element("GUID"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
XElement warehouse = warehouses["0d63057d-99e8-11e6-813b-0003ff000011"];
Dictionary<string, XElement> terms = warehouse.Descendants("Term")
.GroupBy(x => (string)x.Attribute("TargetGUID"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
string value = terms["490ecabf-f011-11e3-b7d9-6c626dc1e098"].Value;
warehouse.SetValue(value);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.