Huang_Hai_Feng
Huang_Hai_Feng

Reputation: 287

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.

Upvotes: 0

Views: 56

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18153

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

enter image description here

Upvotes: 1

Related Questions