从同一个Xml元素反序列化XML属性c#

时间:2018-03-07 18:02:02

标签: c# xml serialization xml-parsing xml-deserialization

我想在C#

中对以下XML进行解除分类
<Configuration>
    <Parameters>
        <Parameter AttrName1 = "AttrValue1"/>
        <Parameter AttrName2 = "AttrValue2"/>
        <Parameter AttrName3 = "AttrValue3"/>
    </Parameters>
</Configuration>

我遇到了麻烦,因为属性名称和值都是相同值的不同。

非常感谢你。

1 个答案:

答案 0 :(得分:2)

您可以使用这些类来序列化/反序列化您的xml。请注意,这是VS中的一项功能:Paste XML as Classes

// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Configuration
{

    private ConfigurationParameter[] parametersField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
    public ConfigurationParameter[] Parameters
    {
        get
        {
            return this.parametersField;
        }
        set
        {
            this.parametersField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ConfigurationParameter
{

    private string attrName1Field;

    private string attrName2Field;

    private string attrName3Field;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string AttrName1
    {
        get
        {
            return this.attrName1Field;
        }
        set
        {
            this.attrName1Field = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string AttrName2
    {
        get
        {
            return this.attrName2Field;
        }
        set
        {
            this.attrName2Field = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string AttrName3
    {
        get
        {
            return this.attrName3Field;
        }
        set
        {
            this.attrName3Field = value;
        }
    }
}