C# 使用重复(但不同)元素反序列化XML
向我提供了一种XML格式,我真的很难将其反序列化:C# 使用重复(但不同)元素反序列化XML,c#,xml,C#,Xml,向我提供了一种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&g
<?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>
然后像这样反序列化:
var recordSerializer = new XmlSerializer(typeof(data));
var myData = (data)recordSerializer.Deserialize(reader);
我确实尝试创建一个自定义的“property”类,但我不知道从那里开始:
public class property
{
public string name { get; set; }
public string value { get; set; }
}
为数据类提供一个propertyclass数组
public class data
{
public string id { get; set; }
[XmlElement("property")]
public property[] Properties { get; set; }
}
你可以这样做
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; }
}
公共类数据
{
公共字符串id{get;set;}
[xmlement(ElementName=“property”)]
公共列表列表a{get;set;}
}
公共类财产
{
[XmlAttribute(“名称”)]
公共字符串名称{get;set;}
[XmlText(typeof(string))]
公共字符串值{get;set;}
}
如果不使用列表,则必须在xml中添加名称空间以区分属性
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; }
}