简体   繁体   English

使用重复(但不同)元素反序列化 XML

[英]Deserialize XML with repeating (but different) elements

I've been supplied supplied an XML format that I'm really struggling to deserialize:我得到了一个 XML 格式,我真的很难反序列化:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<data version='1'>
  <id>1</id>
  <property name='firstName'>John</property>
  <property name='lastName'>Smith</property>
</data>

My issue is when it comes to the "property" element.我的问题是涉及“属性”元素。 I've never had to handle something like that, so I'm not sure how my class should be structured.我从来没有处理过这样的事情,所以我不确定我的 class 应该如何构建。 I'd usually go with:我通常会使用 go :

public class data
{
    public string id { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
}

And then deserialize like so:然后像这样反序列化:

var recordSerializer = new XmlSerializer(typeof(data));
var myData = (data)recordSerializer.Deserialize(reader);

I did try creating a custom "property" class, but I couldn't figure out where to go from there:我确实尝试过创建一个自定义“属性”class,但我不知道从那里到 go 的位置:

public class property
{
   public string name { get; set; }
   public string value { get; set; }
}

You can do this你可以这样做

public class data
{
    public string id { get; set; }

    [XmlElement(ElementName = "property")]
    public List<property> lista { get; set; }
}

public class property
{
    [XmlAttribute("name")]
    public string name { get; set; }
    [XmlText( typeof(string))]
    public string value { get; set; }
}

without using a list would have to add the namespace in xml to differentiate the properties如果不使用列表,则必须在 xml 中添加命名空间以区分属性

Give your data class an array of the propertyclass给你的数据 class 一个属性类的数组

    public class data
    {
        public string id { get; set; }

        [XmlElement("property")]
        public property[] Properties { get; set; }
    }

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

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