XmlSerialization Collection as Array

﹥>﹥吖頭↗ 提交于 2019-12-30 05:04:07

问题


I'm trying to serialize a custom class that needs to use multiple elements of the same name.
I've tried using xmlarray, but it wraps them in another elements.

I want my xml to look like this.

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

My code:

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

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

回答1:


Try just using [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");
    }
}

Note I changed ArrayList to List<string> to clean up the output; in 1.1, StringCollection would be another option, although that has different case-sensitivity rules.




回答2:


(edit: obsoleted - my second post ([XmlElement]) is the way to go - I'm leaving this for posterity in using xsd.exe)

xsd.exe is your friend. Copy the xml you want into a file (foo.xml), then use:

xsd foo.xml
xsd foo.xsd /classes

Now read foo.cs; you can use this either directly, or just for inspiration.

(edit: output snipped - not helpful any more)



来源:https://stackoverflow.com/questions/496488/xmlserialization-collection-as-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!