【问题标题】:Proper usage of XMLRootAttribute in Monotouch在 Monotouch 中正确使用 XMLRootAttribute
【发布时间】:2011-02-17 17:14:04
【问题描述】:

我有一个名为 School 的类,它是可序列化的。当它序列化/反序列化时,我需要将根元素称为学校而不是学校,而无需将类名更改为学校。所以我通过以下方式使用了xmlroot属性:

[XMLRoot(ElementName = "school")]

我也试过了:

[XMLRoot("school")]

这些都没有做任何事情,生成的 XML 文件包含一个名为 School 的根元素。

我错过了什么吗?

【问题讨论】:

    标签: c# .net mono xml-serialization xamarin.ios


    【解决方案1】:

    我看不出可能是什么问题,但以下代码适用于 MonoTouch 4(也许您会发现它与您自己的代码之间存在差异)。

    我定义了一个类:

    [XmlRoot ("School")]
    public class Wrong {
        public string Name { get; set; }
    }
    

    然后我将其序列化为 MemoryStream,然后我将其读入字符串。

            Wrong bad = new Wrong ();
            XmlSerializer ser = new XmlSerializer(typeof(Wrong));
            using (MemoryStream ms = new MemoryStream ()) {
                ser.Serialize (ms, bad);
                ms.Position = 0;
                StreamReader sr = new StreamReader (ms);
                string st = sr.ReadToEnd ();
            }
    

    'st' 的值为:

    <?xml version="1.0" encoding="utf-8"?>
    <School xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    

    【讨论】:

      猜你喜欢
      • 2012-07-25
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      相关资源
      最近更新 更多