Home > Software engineering >  Deserializing an XML array with attributes
Deserializing an XML array with attributes

Time:09-21

I have to consume xml from a tool. In the xml is this part:

<profile>
  <details environment="sd98qlx" severity="critical">
    <detail unit="sec" value="12"/>
    <detail unit="sec" value="25"/>
    <detail unit="msec" value="950"/>
  </details>
</profile>

For deserializing the above with XMLSerializer in C#, how should I use attributes for this on my model class? The problem is the combination of an array with attributes.

CodePudding user response:

Use the sample model class for direction

    [XmlRoot(ElementName = "detail")]
    public class Detail
    {

        [XmlAttribute(AttributeName = "unit")]
        public string Unit { get; set; }

        [XmlAttribute(AttributeName = "value")]
        public int Value { get; set; }
    }

    [XmlRoot(ElementName = "details")]
    public class Details
    {

        [XmlElement(ElementName = "detail")]
        public List<Detail> Detail { get; set; }

        [XmlAttribute(AttributeName = "environment")]
        public string Environment { get; set; }

        [XmlAttribute(AttributeName = "severity")]
        public string Severity { get; set; }
    }

    [XmlRoot(ElementName = "profile")]
    public class Profile
    {

        [XmlElement(ElementName = "details")]
        public Details Details { get; set; }
    }
  • Related