反序列化并获得 xml 具有 2 个具有不同 ID 的属性

Deserialize and get xml having 2 attributes with different ID

我想反序列化并获取具有不同 ID 的 2 个属性的值。

<Attributes><AddressAttribute ID="18"><AddressAttributeValue><Value>Sala 305</Value></AddressAttributeValue></AddressAttribute><AddressAttribute ID="17"><AddressAttributeValue><Value>3434</Value></AddressAttributeValue></AddressAttribute></Attributes>

我修改了这段 C# 代码,但它只有 returns 第一个属性。 请帮助

[XmlRoot(ElementName = "AddressAttributeValue")]

public class AddressAttributeValue
{
    [XmlElement(ElementName = "Value")]

    public string Value { get; set; }

}

[XmlRoot(ElementName = "AddressAttribute")]

public class AddressAttribute
{
    [XmlElement(ElementName = "AddressAttributeValue")]

    public AddressAttributeValue AddressAttributeValue { get; set; }

    [XmlAttribute(AttributeName = "ID")]

    public string ID { get; set; }

}

[XmlRoot(ElementName = "Attributes")]

public class Attributes

{
    [XmlElement(ElementName = "AddressAttribute")]

    public AddressAttribute AddressAttribute { get; set; }

}

 var xmlData= customer.BillingAddress.CustomAttributes;
        XmlSerializer serializer = new XmlSerializer(typeof(Attributes));
        Attributes data;
        using (TextReader reader = new StringReader(xmlData))
        {
            data = (Attributes)serializer.Deserialize(reader);
        }

我应该更改反序列化逻辑的 类 吗???

有时使用 Linq 代替 xml 序列化会更简单

var list = XDocument.Parse(xmlstring).Descendants("AddressAttribute")
        .Select(x => new
        {
            Id = (int)x.Attribute("ID"),
            Value = (string)x.Element("AddressAttributeValue").Element("Value")
        })
        .ToList();
[XmlRoot(ElementName = "Attributes")]
public class Attributes
{
    [XmlElement(ElementName = "AddressAttribute")]

    public AddressAttribute AddressAttribute { get; set; }
}

改为:

[XmlRoot(ElementName = "Attributes")]
public class Attributes
{
    [XmlElement(ElementName = "AddressAttribute")]

    public AddressAttribute[] AddressAttribute { get; set; }
}

因为你需要收集 AddressAttribute 你需要声明为一个数组。