【问题标题】:Deserializing an XML array with attributes反序列化带有属性的 XML 数组
【发布时间】:2021-11-12 12:10:53
【问题描述】:

我必须使用工具中的 xml。在xml中是这部分:

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

为了在 C# 中使用 XMLSerializer 反序列化上述内容,我应该如何在我的模型类上使用属性?问题是数组与属性的组合。

【问题讨论】:

标签: c# xml xmlserializer


【解决方案1】:

使用示例模型类作为方向

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

【讨论】:

  • 虽然 XmlRoot 属性只能在文档中应用一次。根据需要使用 XmlElement 标记列表。
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多