简体   繁体   English

基于元素属性反序列化XML

[英]Deserializing XML Based on Element Attributes

I am trying to deserialize an XML file within a C# program that looks like this: 我正在尝试在C#程序中反序列化XML文件,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<Addresses>
  <ListName>Flowers</ListName>
  <Address contextRef="RP.CC">Some Address</Address>
  <Address contextRef="RP.BE">Some Other Address</Address>
  <Address contextRef="RP.BV">Yet Another Address</Address>
  <Address contextRef="RP.CAL">Wow, I Can't Believe It's Another Address</Address>
</Addresses>

I do not have any control over the format of this file. 我对此文件的格式没有任何控制权。 But, it will always have some combination of these 4 Address elements (ie these 4 contextRef attribute values are the only ones used) with differing element values each time. 但是,它将始终具有这4个Address元素的某种组合(即,仅使用这4个contextRef属性值),并且每次具有不同的元素值。

Now, instead of deserializing into an Address array, I need to send them to individual properties within an Addresses object. 现在,无需将其反序列化为一个Address数组,而是需要将它们发送到Addresses对象内的各个属性。 My Current implementation uses an array and then a setter method to set these properties based on the contextRef as so: 我的当前实现使用一个数组,然后使用一个setter方法根据contextRef设置这些属性,如下所示:

public class Addresses
{
    [XmlElement("ListName")]
    public string ListName { get; set; }

    private Address[] _addresses;

    [XmlElement("Address")]
    public Address[] AddressesArray
    {
        get
        {
            return _addresses;
        }
        set
        {
            _addresses = value;
            SetAddress();
        }
    }

    [XmlIgnore]
    public Address AddressG21 { get; set; }

    [XmlIgnore]
    public Address AddressG22 { get; set; }

    [XmlIgnore]
    public Address AddressG23 { get; set; }

    [XmlIgnore]
    public Address AddressG9 { get; set; }

    private void SetAddress()
    {
        foreach (var address in _addresses)
        {
            if (address.ContextRef == "RP.CC")
            {
                AddressG21 = address;
            }
            else if (address.ContextRef == "RP.BE")
            {
                AddressG22 = address;
            }
            else if (address.ContextRef == "RP.BV")
            {
                AddressG23 = address;
            }
            else if (address.ContextRef == "RP.CAL")
            {
                AddressG9 = address;
            }
        }
    }
}

Where the Address object is defined as so: 地址对象的定义如下:

public class Address
{
    private string valueField;

    /// <remarks/>
    [XmlText]
    public string Value
    {
        get
        {
            return this.valueField;
        }
        set
        {
            this.valueField = value;
        }
    }

    [XmlAttribute("contextRef")]
    public string ContextRef { get; set; }
}

So, my question is, is there a neater/better way of deserializing this XML directly into the AddressG21, etc. object properties without first using the Address array? 因此,我的问题是,是否有一种更整洁/更好的方法来将此XML直接反序列化为AddressG21等对象属性,而无需先使用Address数组?

Thanks in advance. 提前致谢。

I would use xml linq and create a dictionary in the class 我将使用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);

            Addresses addresses = doc.Descendants("Addresses").Select(x => new Addresses() {
                ListName = (string)x.Element("ListName"),
                dict = x.Elements("Address")
                   .GroupBy(y => (string)y.Attribute("contextRef"), z => (string)z)
                   .ToDictionary(y => y.Key, z => z.FirstOrDefault())
            }).FirstOrDefault();

        }
    }
    public class Addresses
    {
        public string ListName { get; set; }
        public Dictionary<string, string> dict { get; set; }
    }

}

If you had multiple Addresses elements then use this 如果您有多个Addresses元素,请使用此

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);

            List<Addresses> addresses = doc.Descendants("Addresses").Select(x => new Addresses() {
                ListName = (string)x.Element("ListName"),
                dict = x.Elements("Address")
                   .GroupBy(y => (string)y.Attribute("contextRef"), z => (string)z)
                   .ToDictionary(y => y.Key, z => z.FirstOrDefault())
            }).ToList();

        }
    }
    public class Addresses
    {
        public string ListName { get; set; }
        public Dictionary<string, string> dict { get; set; }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM