繁体   English   中英

我如何序列化带有属性的类

[英]How can I serialize a class with an attribute

我有一堂课

[XmlRoot]
<snip>

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

<snip>

可以在编译时..但是在运行时,在行处发生异常

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

因为“ x:uid”中的无效字符。.类中的元素需要具有“ x:uid”属性才能进行本地化。.我该怎么做?

谢谢!

要设置属性的名称空间,您需要使用XmlAttributeAttributeNamespace属性。

如果用于该名称空间的前缀特别是“ 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();
    }
}

产生:

<?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"/>

您需要指定实际的名称空间-而不是别名(由作者决定):

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

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

public string Uid {get;set;}

据我所知,您不能在C#XML属性声明中使用名称空间前缀。 尝试仅使用“ uid”而不使用“ x:”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM