【问题标题】:Change XmlElement name for XML serialisation更改 XML 序列化的 XmlElement 名称
【发布时间】:2011-09-17 03:09:29
【问题描述】:

我们有以下代码:

[Serializable]
public class Class1
{
    [XmlElement("description")]
    public string Description { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var list = new List<Class1> {new Class1() {Description = "Desc1"}, new Class1() {Description = "Desc2"}};
        var serializer = new XmlSerializer(typeof(List<Class1>), new XmlRootAttribute("root"));
        var ms = new MemoryStream();
        serializer.Serialize(ms, list);
        ms.Position = 0;
        var result = new StreamReader(ms).ReadToEnd();
    }
}

执行后我们将在'result'变量中有以下内容:

<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Class1>
    <description>Desc1</description>
  </Class1>
  <Class1>
    <description>Desc2</description>
  </Class1>
</root>

问题是:如何在不更改类名的情况下将 xml 元素名称从“Class1”更改为“Item1”?

【问题讨论】:

    标签: c# .net xml serialization


    【解决方案1】:

    在课堂上也使用XmlTypeAttribute

    [XmlType(TypeName="ElementName")]
    [Serializable]
    public class Class1 { ...
    

    编辑:从XmlRootAttribute 更新为XmlTypeAttribute。前者适用于传递给序列化程序的类型是属性类型(此处为Class1),但当存在包装类型时(此处为List&lt;Class1&gt;)则不行。 XmlType 的工作在文档中并不清楚(我的重点):

    控制 XmlSerializer 序列化属性目标时生成的 XML schema

    感谢 Bala R 的 answer

    【讨论】:

    • 我不认为XmlElementAttribute可以应用于类。[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple = true)] public class XmlElementAttribute : Attribute并且没有AttributeTargets.Class
    • System.Xml.Serialization.XmlElementAttribute 有 AttributeUsage: Field |参数 |物业 | ReturnValue 但不是类型
    • @TheOtherGuy... 应该,看看MSDN 上的示例...但是List&lt;Class1&gt; 搞砸了。
    • 有什么方法可以根据属性名称生成动态名称? (即:而不是让 [XmlElement("description")] 有一些动态代码,比如 CurrentName.ToLowerCase() )和 Description 将是描述?
    【解决方案2】:

    您可以为此使用XmlTypeAttribute.TypeName

    试试这个Class1定义

        [XmlType(TypeName = "Item1")]
        [Serializable]
        public class Class1
        {
            [XmlElement("description")]
            public string Description { get; set; }
        }
    

    【讨论】:

    • 有什么方法可以根据属性名称生成动态名称? (即:而不是让 [XmlElement("description")] 有一些动态代码,比如 CurrentName.ToLowerCase() )和 Description 将是描述?
    猜你喜欢
    • 1970-01-01
    • 2023-03-02
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多