【问题标题】:Deserializing XML attributes from the same Xml element c#反序列化来自相同 Xml 元素 c# 的 XML 属性
【发布时间】:2018-03-07 18:02:02
【问题描述】:

我想在 C# 中反序列化以下 XML

<Configuration>
    <Parameters>
        <Parameter AttrName1 = "AttrValue1"/>
        <Parameter AttrName2 = "AttrValue2"/>
        <Parameter AttrName3 = "AttrValue3"/>
    </Parameters>
</Configuration>

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

非常感谢。

【问题讨论】:

  • 将 XML 粘贴为类,首先创建有效的 xml
  • Xml 是我的输入。我需要阅读、更新然后可能保存。
  • 出于兴趣,为什么需要三个不同的参数名称。例如,它们都可以称为 AttrName。只是好奇。 ??????

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


【解决方案1】:

您可以使用这些类来序列化/反序列化您的 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;
        }
    }
}

【讨论】:

  • 从来不知道这个功能。我自己手动写的。我将看看是否可以使用它来将我的 C# 项目中的结果与我自己的代码进行比较..?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多