如何正确反序列化XML属性和数组?

时间:2017-08-25 08:45:27

标签: c# xml deserialization datacontract

我正在做一个C#项目,我有一个用XML编码的对象;一个示例实例是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Entity Type="StartRunTestSetResponse">
    <Fields>
        <Field Name="SuccessStaus">
            <Value>2</Value>
        </Field>
        <Field Name="info">
            <Value></Value>
        </Field>
    </Fields>
</Entity>

我需要属性信息,因为它是对象所具有的Key-Value对中的必需品。

我的反序列化语法如下所示:

[DataContract(Name="Entity", Namespace="")]
[XmlSerializerFormat]
[KnownType(typeof(SRTSRField))]
[KnownType(typeof(SRTSRValue))]
public class StartRunTestSetResponse
{
    [DataMember(Name="Type"), XmlAttribute("Type")]
    public string type { get; set; }

    [DataMember(Name = "Fields", IsRequired = true), XmlElement("Fields")]
    public List<SRTSRField> fields { get; set; }

    internal StartRunTestSetResponse() { fields = new List<SRTSRField>(); }
}
[DataContract(Name = "Field", Namespace = "")]
[KnownType(typeof(SRTSRValue))]
public class SRTSRField
{
    [DataMember(Name = "Name"), XmlAttribute("Name")]
    public string name {get; set;}

    [DataMember(Name = "Value"), XmlElement("Value")]
    public SRTSRValue value { get; set; }
}
[DataContract(Name = "Value", Namespace = "")]
public class SRTSRValue
{
    [DataMember, XmlText]
    public string value { get; set; }
}

现在,它不起作用;此时它会解析为Fields元素,然后它的任何子元素都是null

3 个答案:

答案 0 :(得分:2)

您可以简化模型

public class Entity
{
    [XmlAttribute]
    public string Type { get; set; }
    [XmlArrayItem("Field")]
    public Field[] Fields { get; set; }
}

public class Field
{
    [XmlAttribute]
    public string Name { get; set; }
    public string Value { get; set; }
}

所以反序列化将是

XmlSerializer ser = new XmlSerializer(typeof(Entity));
using (StringReader sr = new StringReader(xmlstring))
{
    var entity = (Entity)ser.Deserialize(sr);

}

答案 1 :(得分:0)

factory.createPeerConnection(iceServers, sdpMediaConstraints, this);

Createdy:http://xmltocsharp.azurewebsites.net/ 这真的很有用

答案 2 :(得分:0)

我会使用xml linq创建一个字典。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication74
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string,int?> dict1 = doc.Descendants("Field")
                .GroupBy(x => (string)x.Attribute("Name"), y => string.IsNullOrEmpty((string)y.Element("Value")) ? null : (int?)y.Element("Value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());


        }

    }



}