【问题标题】:Get value of xml attribute when desearlizing xml to c#将xml反序列化为c#时获取xml属性的值
【发布时间】:2020-04-30 06:14:27
【问题描述】:

我要做的是从下面 xml 的 Included_By_Organization 集合中的 ID 标记上的 type 属性中获取属性值。我可以很好地获取值,但属性返回 null。

包含在组织对象示例中:

Type: null

XML

<wd:Included_by_Organizations wd:Descriptor="RU7860 Europe Forwarding Overhead">
        <wd:ID wd:type="WID">b8129574800601751d8538accb023f35</wd:ID>
        <wd:ID wd:type="Organization_Reference_ID">RU7860</wd:ID>
        <wd:ID wd:type="Custom_Organization_Reference_ID">RU7860</wd:ID>
</wd:Included_by_Organizations>

xml 数组的类

        [XmlAttribute("type")]
        public string Type { get; set; }

        [XmlText]
        public string Value { get; set; }

        public IncludedByOrganization()
        {
        }

获取 xml 值的类

    [XmlElement("Reference_ID")]
    public string CostCenterId { get; set; }

    [XmlElement("code")]
    public string Code { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlArray("Included_by_Organizations")]
    [XmlArrayItem("ID")]
    public IncludedByOrganization[] IncludedByOrganization { get; set; }

去沙化方法

        ReportData reportDataList = new ReportData();
        XmlSerializer serializer = new XmlSerializer(typeof(ReportData));

        using (var reader = XmlReader.Create(filePath))
        {
            ReportData reportData = (ReportData)serializer.Deserialize(reader);
            reportDataList = reportData;
        }

        return reportDataList;

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    根据您的示例,我创建了另一个示例并设法阅读了type。

    [Serializable, XmlRoot()]
    public class XML
    {
        [XmlArray("Included_by_Organizations")]
        [XmlArrayItem("ID")]
        public IncludedByOrganization[] IncludedByOrganization { get; set; }
    }
    

    注意[Serialization, XmlRoot()] 的属性。

    [Serializable]
    public class IncludedByOrganization
    {
        [XmlAttribute("type")]
        public string Type { get; set; }
    
        [XmlText]
        public string Value { get; set; }
    
        public IncludedByOrganization()
        {
        }
    }
    

    还添加了[Serialization]属性。

    文字示例:

    <?xml version="1.0" encoding="UTF-8"?>
    <XML>
        <Included_by_Organizations Descriptor="RU7860 Europe Forwarding Overhead">
            <ID type="WID">b8129574800601751d8538accb023f35</ID>
            <ID type="Organization_Reference_ID">RU7860</ID>
            <ID type="Custom_Organization_Reference_ID">RU7860</ID>
        </Included_by_Organizations>
    </XML>
    

    示例存储在string xml。

    XmlSerializer serializer = new XmlSerializer(typeof(XML));
    var reader = new StringReader(xml);
    var deserialized = serializer.Deserialize(reader);
    

    结果:

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2023-04-07
      • 2021-12-13
      相关资源
      最近更新 更多