c# - 在 Monotouch 中正确使用 XMLRootAttribute

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

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

[XMLRoot(ElementName = "学校")]

我也试过:

[XMLRoot("学校")]

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

我错过了什么吗?

最佳答案

我看不出可能是什么问题,但以下代码适用于 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" />

关于c# - 在 Monotouch 中正确使用 XMLRootAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5032199/

相关文章:

c# - PowerShell - 从 .csproj 文件获取版本

c# - 添加对 Web 服务的引用

c# - CollectionChanged 和 IList of Items - 为什么困难

C# .NET 轨迹球支持 - 但不是作为鼠标!

c# - 如何禁用 MARS 并规避 "MARS is not yet implemented"-exception”?

c# - Windows 应用商店应用程序中的页面全局键盘事件

c# - 您如何在 LINQ 中进行自定义排序,最后始终为 null?

c# - dll 请求的执行级别

c# - 使用 Mono 为 Linux 创建可执行文件?

android - 在 Mac 上使用 Jenkins 构建 Xamarin Android 项目错误 MSB3073