将xml解除武装到c#时获取xml属性的值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将xml解除武装到c#时获取xml属性的值相关的知识,希望对你有一定的参考价值。

我想做的是从下面xml的Included_By_Organization集合中ID标记的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;
答案

根据您的示例,我创建了另一个示例,并设法读取了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);

结果:

enter image description here

以上是关于将xml解除武装到c#时获取xml属性的值的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 xslt 获取 XML 的属性值和代码作为 html 的值

解析 XML,获取特定名称的深层元素。 (C#)

【求助】Dom4j 生成xml,节点增加属性时,属性值中有特殊字符,如何做到不转义

获取元素的值并使其成为 XSLT 中属性的值?

在Tomcat的安装目录下conf目录下的server.xml文件中增加一个xml代码片段,该代码片段中每个属性的含义与用途

如何将 XML 属性值添加到包含对象的字典中