简体   繁体   中英

De-Serialize of Xml Collections

I've a XML string like below:

<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>

Below is my c# code. BTW, I have tried using xmlArray and xmlArrayItem attribute, but no vail.

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

How to de-Serialize this XML into c# objects?

I just can't figure it out.

You might need some changes in your Data Structure. Please note the changes from your original structure, especially how "Properties/Property" is being dealt with

Xml to CSharp would be a good place to refer when you want to create C# Data structure corresponding to your Xml.

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

That would give an output as

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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