DataContract XML序列化和XML属性 [英] DataContract XML serialization and XML attributes

查看:110
本文介绍了DataContract XML序列化和XML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能这个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;
}

您可以用下面的code测试:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆