我有一个类有
[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/