【问题标题】:De-Serialize of Xml CollectionsXml 集合的反序列化
【发布时间】:2019-01-25 19:00:55
【问题描述】:

我有一个如下的 XML 字符串:

<ArrayOfObject>
    <Object>
        <Properties>
            <Property>
                <Name>TaskId1</Name>
                <Value>xxx</Value>
            </Property>
            <Property>
               <Name>Name</Name>
               <Value>demo</Value>
            </Property>
        </Properties>
    </Object>

    <Object>
        <Properties>
            <Property>
                <Name>TaskId2</Name>
                <Value>xxx</Value>
            </Property>
            <Property>
               <Name>Name</Name>
               <Value>demo2</Value>
            </Property>
        </Properties>
    </Object>
 </ArrayOfObject>

下面是我的 C# 代码。顺便说一句,我尝试过使用 xmlArrayxmlArrayItem 属性,但没有成功。

[XmlRoot(ElementName = "ArrayOfObject",  IsNullable = false)]
public class GetTaskListResponse
{
    [XmlArray("Object")]
    public List<ObjectList> Objects { get; set; }
}

public class ObjectList
{
    [XmlArray("Properties")]
    [XmlArrayItem("Property")]
    public List<Property> PropertyList { get; set; }
}

public class Property
{
    public string Name { get; set; }
    public string Value { get; set; }
}

如何将此 XML 反序列化为 c# 对象?

我就是想不通。

【问题讨论】:

  • "我尝试过使用 xmlArray 和 xmlArrayItem 属性,但没有成功。"请准确显示您尝试过的内容。如果这里有人会写出与您自己尝试过的完全相同的答案怎么办?这对你有帮助吗?我怀疑是这样。因此,请提供相关信息,方便我们为您提供帮助。

标签: c# collections xml-deserialization


【解决方案1】:

您可能需要对数据结构进行一些更改。请注意原始结构的变化,尤其是“属性/属性”的处理方式

Xml to CSharp 是您想要创建与您的 Xml 对应的 C# 数据结构时参考的好地方。

[XmlRoot(ElementName="Property")]
public class Property 
{
   [XmlElement(ElementName="Name")]
   public string Name { get; set; }
   [XmlElement(ElementName="Value")]
   public string Value { get; set; }
}

[XmlRoot(ElementName="Properties")]
public class Properties 
{
    [XmlElement(ElementName="Property")]
    public List<Property> Property { get; set; }
}

[XmlRoot(ElementName="Object")]
public class Object 
{
   [XmlElement(ElementName="Properties")]
   public Properties Properties { get; set; }
}

[XmlRoot(ElementName="ArrayOfObject")]
public class GetTaskListResponse 
{
   [XmlElement(ElementName="Object")]
   public List<Object> Object { get; set; }
}

这将给出一个输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多