DataContract XML 序列化和 XML 属性 [英] DataContract XML serialization and XML attributes
问题描述
是否可以将此 XML 反序列化为标有 DataContract 属性的对象?
Is it possible to deserialize this XML into an object marked with the DataContract attribute?
<root>
<distance units="m">1000</distance>
</root>
如您所见,有单位"属性.我不相信这是支持的.还是我错了?
As you may see there is "units" attribute. I don't believe that's supported. Or am I wrong?
推荐答案
这可以实现,但您必须通过将 [XmlSerializerFormat]
属性应用于 DataContract 来覆盖默认序列化程序.虽然可以做到,但它的性能不如默认的序列化器,因此请谨慎使用.
This can be achieved, but you will have to override the default serializer by applying the [XmlSerializerFormat]
attribute to the DataContract. Although it can be done, this does not perform as well as the default serializer, so use it with caution.
下面的类结构会给你你想要的结果:
The following class structure will give you the result you are after:
using ...
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Xml.Serialization;
[DataContract]
[XmlSerializerFormat]
public class root
{
public distance distance=new distance();
}
[DataContract]
public class distance
{
[DataMember, XmlAttribute]
public string units="m";
[DataMember, XmlText]
public int value=1000;
}
您可以使用以下代码进行测试:
You can test this with the following code:
root mc = new root();
XmlSerializer ser = new XmlSerializer(typeof(root));
StringWriter sw = new StringWriter();
ser.Serialize(sw, mc);
Console.WriteLine(sw.ToString());
Console.ReadKey();
输出将是:
<?xml version="1.0" encoding="utf-16"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<distance units="m">1000</distance>
</root>
这篇关于DataContract XML 序列化和 XML 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!