【问题标题】:XmlSerialization Collection as ArrayXmlSerialization 集合作为数组
【发布时间】:2009-07-29 05:30:40
【问题描述】:

我正在尝试序列化需要使用多个同名元素的自定义类。
我尝试过使用 xmlarray,但它将它们包装在另一个元素中。

我希望我的 xml 看起来像这样。

<root>
     <trees>some text</trees>
     <trees>some more text</trees>
</root>

我的代码:

[Serializable(), XmlRoot("root")]
public class test
{
      [XmlArray("trees")]
      public ArrayList MyProp1 = new ArrayList();

      public test()
      {
           MyProp1.Add("some text");
           MyProp1.Add("some more text");  
      }
}

【问题讨论】:

  • 您是否尝试过设置属性 XmlArrayItem(typeof(System.String)) 以及 XMLArray ?
  • 是的,它会在 some textsome more text 下面创建类似 xml 的东西
  • 好问题,坏标题。标题应为“如何使用 XmlSerializer 展平数组/列表/集合”

标签: c# .net xml-serialization


【解决方案1】:

尝试只使用[XmlElement("trees")]:

[Serializable(), XmlRoot("root")]
public class test
{
    [XmlElement("trees")]
    public List<string> MyProp1 = new List<string>();

    public test()
    {
        MyProp1.Add("some text");
        MyProp1.Add("some more text");
    }
}

注意我将ArrayList 更改为List&lt;string&gt; 以清理输出;在 1.1 中,StringCollection 将是另一种选择,尽管它有不同的区分大小写规则。

【讨论】:

  • 谢谢!正是我想要的!
【解决方案2】:

(编辑:已过时 - 我的 second post ([XmlElement]) 是要走的路 - 我将把它留给后代使用 xsd.exe

xsd.exe 是你的朋友。将你想要的xml复制到一个文件中(foo.xml),然后使用:

xsd foo.xml
xsd foo.xsd /classes

现在阅读foo.cs;您可以直接使用它,也可以只是为了获得灵感。

(编辑:输出被剪断 - 不再有用)

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    相关资源
    最近更新 更多