c# - 如何序列化具有属性的类

标签 c# xml-serialization

我有一个类有

[XmlRoot]
<snip>

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

<snip>

在编译时没问题...但是在运行时, 行发生异常

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

因为“x:uid”中的无效字符.. 出于本地化目的,我类(class)中的元素需要具有“x:uid”属性。 我该怎么做??

谢谢!

最佳答案

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

如果用于该 namespace 的前缀是“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"/>

关于c# - 如何序列化具有属性的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/688985/

相关文章:

c# - 如何调用类型为 T 的方法将 T 作为字符串或 "T"传递

c# - 读取 System.Diagnostics.Debug 窗口

c# - 是否可以通过 Resharper 对代码进行排序?

c# - 将字符串属性序列化为属性,即使字符串为空

.net - 命名空间未通过 DataContractSerializer 从 XML 根中删除

c# - Group By 在两个字段之间来回链接

c# - 将具体的 Task<TImplementation> 分配给 Task<TInterface> 类型的变量

java - JAXB 将多个对象编码到一个文件

c# - 反序列化 KeyValuePairs 列表

xml - namespace 中名为 'name' 的 XML 元素引用了不同的类型