从包含动态子类的类生成的xml

时间:2018-07-05 09:38:19

标签: c# asp.net-mvc xml-parsing

我需要从包含可能会更改的子类的类中生成XML,为实现此目的,我创建了如下所示的基类;

//XML output format; 
   <SYSMessage>
      <messageType />
      <documentGenerationTime />

    //Some dynamic XML elements generated from subclass
    </SYSMessage>

 [Serializable()]
    public class SYSMessage<T>
    {

        [XmlElement("messageType")]
        public messageType messageType { get; set; } = new messageType();
        [XmlElement("documentGenerationTime")]
        public documentGenerationTime documentGenerationTime { get; set; }


        [XmlElement("recordData")]
        public T recordData { get; set; } = new T();
    }

这就是我的用法;

public class A
    {
        [XmlElement("B")]
        public B customproperty1 { get; set; } = new B();
        [XmlElement("C")]
        public C customproperty2 { get; set; } = new C();
    }
    public class B
    {
        public string Value { get; set; }
    }
public class C
    {
        public class D { get; set; } = new D();
    }
public class D
    {
        public string value { get; set; } = "some string";
    }

我这样测试;

var obj = new SYSMessage<A>();
var output = SerializeToString(obj);

预期结果:

<SYSMessage>
          <messageType version="0" />
          <documentGenerationTime />
          <author>
            <healthcareProvider version="0" />
          </author>
        <recordData>
           <B value="some string" />
           <C>
             <D value="some string" />
           </C>
        </recordData>
</SYSMessage>

ofc它不起作用..如果我删除子类,输出就可以了。我如何获得它? 或者我很乐意接受指导或类似的例子。

0 个答案:

没有答案