1

I want to deserialize an xml file using c#.

the file has this form:

<parent>
   <TotProd Name="Total Produce Kwh">
       <Time value="00:00:00">10</Time>
       <Time value="00:30:00">10</Time>
        ............ 
   </TotProd>
   <ProdToNet Name="Produce to Net (iec)">
       <Time value="00:00:00">10</Time>
       <Time value="00:30:00">10</Time>
        ...........
   </ProdToNet> .....
</parent>

I want to deserialize all child elements of parent into a List<Myclass> with TotProd/ProdToNet as a property of Myclass.

How can i do this.

1
  • Provide your class details also.. Commented Jul 31, 2012 at 8:44

1 Answer 1

4

You can use a common class for both elements, if they have the same structure:

public class Time{
    [XmlAttribute]
    public string value {get; set; }
    [XmlText]
    public string Text {get;set;} // this will hold the innerText value ("10") of <Time>
}

public class Prod{

    [XmlAttribute]
    public string Name {get; set; }
    [XmlElement("Time")]
    public List<Time> Time {get; set; }
}

[XmlRoot("parent")]
public class Parent{
    [XmlElement(ElementName="ProdToNet", Type=typeof(Prod))]
    [XmlElement(ElementName="TotProd", Type=typeof(Prod))]
    public List<Prod> {get; set;}
}

UPDATE: The Time:value seems like a TimeSpan duration object, so it can be presented as:

public class Time{
    [XmlIgnore]
    public TimeSpan _duration;

    [XmlAttribute(DataType = "duration")]
    public string value
        get
        {
            return XmlConvert.ToString(this._duration);
        }

        set
        {
            this._duration = XmlConvert.ToTimeSpan(value);
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I also had to add XmlChoiceIdentifier attribute as displayed here "msdn.microsoft.com/en-us/library/…". it would be nice if it was possible to deserialize all child elements to a list even without know the name of the elements in advance.
You can use a [XmlAnyElement] attribute to handle all elements without knowing their names, and then just deserialize them manually: msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.