【问题标题】:How do you rename the child XML elements used in an XML Serialized List<string>?如何重命名 XML 序列化列表<string> 中使用的子 XML 元素?
【发布时间】:2008-11-26 20:05:42
【问题描述】:

我正在将我的类序列化为 XML,其中一个属性的类型为 List

public class MyClass {
    ...
    public List<string> Properties { get; set; }
    ...
}

通过序列化此类创建的 XML 如下所示:

<MyClass>
    ...
    <Properties>
        <string>somethinghere</string>
        <string>somethinghere</string>
    </Properties>
    ...
</MyClass>

现在我的问题。我怎样才能改变我的类来实现这样的 XML:

<MyClass>
    ...
    <Properties>
        <Property>somethinghere</Property>
        <Property>somethinghere</Property>
    </Properties>
    ...
</MyClass>

序列化后。感谢您的帮助!

【问题讨论】:

    标签: c# .net xml serialization


    【解决方案1】:

    试试XmlArrayItemAttribute:

    using System;
    using System.IO;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    
    public class Program
    {
        [XmlArrayItem("Property")]
        public List<string> Properties = new List<string>();
    
        public static void Main(string[] args)
        {
            Program program = new Program();
            program.Properties.Add("test1");
            program.Properties.Add("test2");
            program.Properties.Add("test3");
    
            XmlSerializer xser = new XmlSerializer(typeof(Program));
            xser.Serialize(new FileStream("test.xml", FileMode.Create), program);
        }
    }
    

    test.xml:

    <?xml version="1.0"?>
    <Program xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Properties>
        <Property>test1</Property>
        <Property>test2</Property>
        <Property>test3</Property>
      </Properties>
    </Program>
    

    【讨论】:

      【解决方案2】:

      在您的 Properties 成员声明之前添加 [XmlElement("Property")]

      【讨论】:

      • 当我在 MyClass 节点下生成属性 XML 叶之前使用 [XmlElement("Property")] 时(它们应该放在“属性”下)。使用 [XmlArrayItem("Property")] 解决了我的问题。感谢您的帮助
      【解决方案3】:

      如果您想在 WCF 服务中执行此操作并仍然使用 DataContractSerializer,您可以简单地定义一个新的 List 子类:

      [CollectionDataContract(ItemName="Property")]
      public class PropertyList: List<string>
      {
          public PropertyList() { }
          public PropertyList(IEnumerable<string> source) : base(source) { }
      }
      

      然后,在您要序列化的类中,只需将成员指定为:

      [DataMember]
      public PropertyList Properties;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-21
        相关资源
        最近更新 更多