反序列化并获取具有2个具有不同ID

时间:2018-03-17 22:36:48

标签: c# .net xml-deserialization

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

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

我对此C#代码进行了处理,但它只返回第一个属性。 请帮忙

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

我应该更改Deserialize logic ???的类吗?

2 个答案:

答案 0 :(得分:0)

有时使用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();

答案 1 :(得分:0)

[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,因此需要将其声明为数组。