如何反序列化此XML

时间:2018-04-16 11:21:13

标签: c# asp.net xml

如何从我的示例中正确地反序列化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:

[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:

[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; }
}

问题:如何将Warehouse的GUID属性值设置为SourceWarehouseGuid?

2 个答案:

答案 0 :(得分:1)

您可以实现自定义反序列化逻辑,只需在依赖项上设置值即可。见这里:https://docs.microsoft.com/en-us/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;
     }
}

答案 1 :(得分:-1)

我喜欢使用字典和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);

        }
    }
}