如何使用属性序列化类

1 c# xml-serialization

我有一堂课

[XmlRoot]
<snip>

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

<snip>
Run Code Online (Sandbox Code Playgroud)

它在编译时是正常的..但是在运行时,异常发生在行

XmlSerializer serializer = new XmlSerializer(typeof(myClass));
Run Code Online (Sandbox Code Playgroud)

因为"x:uid"中的无效字符..我的类中的元素需要有一个"x:uid"属性用于本地化目的..我该怎么做?

谢谢!

Gre*_*ech 9

要设置属性的命名空间,您需要使用Namespace属性XmlAttributeAttribute.

如果用于该命名空间的前缀是"x"特别重要,那么您可以XmlSerializerNamespaces在进行序列化时使用该类来控制它,可选地使用XmlNamespaceDeclarationsAttribute.


这是一个有效的例子:

[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();
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个产生:

<?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"/>
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 5

您需要指定实际的命名空间 - 而不是别名(编写者将决定):

[XmlAttribute(AttributeName="uid", Namespace="http://my/full/namespace")]
public string uid;
Run Code Online (Sandbox Code Playgroud)

请注意,const string对于命名空间等通常使用" ".此外,公共字段不是一个好主意 - 使用C#3.0可能会有(xml属性未显示):

public string Uid {get;set;}
Run Code Online (Sandbox Code Playgroud)