我如何序列化一个类的属性
我有了
[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 $ C $ 。C>
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"/>