本文介绍了反序列随机/未知类型与XmlSerializer的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的XmlSerializer与服务进行通信。这不是一个常规的SOAP服务,它有其自己的XML对象类型。例如,我可以问一个<能力> 的对象,但它可能会返回一个<异常> 。所以,换句话说,我要处理的随机XML文档类型。我不过,知道我要处理哪些类型。

I am using XmlSerializer to communicate with a service. This is not a regular SOAP service, it has its own XML object types. For example, I may ask for a <Capabilities> object, but it may return an <Exception>. So, in other words, I have to deal with random XML document types. I do however, know which types I have to deal with.

我所要做的是找到一种通用的方法序列化/反序列化这些文档。的问题是,XmlSerializer的需要知道在创建阶段的类型。

What I am trying to do is to find a generic approach to serialize/deserialize these documents. The problem is that the XmlSerializer needs to know the type at creation stage.

这些没有封装在一个共同的根元素,所以做一个基类,并使用 [XmlInclude] 属性不会在这种情况下工作:

These are NOT encapsulated in a common root element, so making a base class and using the [XmlInclude] attribute does NOT work in this case:

[XmlInclude(typeof(Exception))]
[XmlInclude(typeof(Capabilities))]
public abstract class BaseClass
{
  public BaseClass()
  {
    SchemaLocation = "test";
  }

  [XmlAttribute("schemaLocation")]
  public String SchemaLocation { get; set; }
}

[XmlRoot("Exception")]
public class Exception : BaseClass
{
  public Exception():base()
  {
  }
  [XmlElement]
  public String Message { set; get; }
}

[XmlRoot("Capabilities")]
public class Capabilities : BaseClass
{
  public Capabilities() : base()
  {}
  [XmlElement]
  public String ServiceName { set; get; }
}

我的解决方案迄今与XmlReader的手动探测根元素,然后创建一个XmlSerializer实例之前将其映射到正确的类型。

My solution so far is to probe the root element manually with the XmlReader, and then map it to the correct type before creating an XmlSerializer instance.

是否有这样做的没有更好的办法?

Is there any better way of doing this ?

推荐答案

我不知道是好是坏,但你可以尝试 DynamicObject 办法。http://blogs.msdn.com/b/csharpfaq/archive/2009/10/19/dynamic-in-c-4-0-creating-wrappers-with-dynamicobject.aspx

I don't know whether it is better or not but you may try DynamicObject approach.http://blogs.msdn.com/b/csharpfaq/archive/2009/10/19/dynamic-in-c-4-0-creating-wrappers-with-dynamicobject.aspx

这篇关于反序列随机/未知类型与XmlSerializer的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:53