我如何序列化一个类的属性 [英] How can I serialize a class with an attribute

查看:132
本文介绍了我如何序列化一个类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了

[XmlRoot]
<snip>

[XmlAttribute(AttributeName="x:uid")]
public string uid;

<snip>



这是确定在编译的时候。但是在运行时,
例外发生在行

It is OK At compile time.. however at runtime, exception occurs at line

XmlSerializer serializer = new XmlSerializer(typeof(myClass));

由于在X:UID无效字符的..
中的元素我类需要有一个X:UID!为本地化的目的..
我怎么能这样做?

because of the invalid character in "x:uid".. The element in my class needs to have an "x:uid" attribute for localization purposes.. How can I do that??

感谢

推荐答案

要设置属性的命名空间,你需要使用的 命名空间 财产 XmlAttributeAttribute

To set the namespace of the attribute, you'll need to use the Namespace property of XmlAttributeAttribute.

如果这是特别重要的是用于该命名空间前缀为x,那么你可以使用的 XmlSerializerNamespaces 系列化做的时候,任选具有的 =http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlnamespacedeclarationsattribute.aspx> XmlNamespaceDeclarationsAttribute

If it's particularly important that the prefix used for that namespace is "x" then you can control this using the XmlSerializerNamespaces class when doing serialization, optionally with XmlNamespaceDeclarationsAttribute.


下面是一个工作的例子:

Here's a working example:

[XmlRoot(Namespace = "http://foo")]
public class MyClass
{
    private XmlSerializerNamespaces xmlns;

    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Xmlns 
    {
        get
        {
            if (xmlns == null)
            {
                xmlns = new XmlSerializerNamespaces();
                xmlns.Add("x", "http://xxx");
            }
            return xmlns;
        }
        set { xmlns = value; }
    }

    [XmlAttribute("uid", Namespace = "http://xxx")]
    public int Uid { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var s = new XmlSerializer(typeof(MyClass));
        s.Serialize(Console.Out, new MyClass { Uid = 123 });
        Console.ReadLine();
    }
}



主要生产:

Which produces:

<?xml version="1.0" encoding="ibm850"?>
<MyClass 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:x="http://xxx" 
    x:uid="123" 
    xmlns="http://foo"/>

这篇关于我如何序列化一个类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆