[英]Generate mock XML file from C# class hierachy
In order to generate UBL-order documents in XML, I have created 44 classes in C# using Xml.Serialization. 为了生成XML格式的UBL顺序文档,我使用Xml.Serialization在C#中创建了44个类。 The class consist of a root class "OrderType" which contains a lot of properties (classes), which again contains more properties.
该类由一个包含许多属性(类)的根类“ OrderType”组成,该属性又包含更多的属性。
In order to test that the classes always will build a XML document that will pass a validation. 为了测试这些类始终会构建一个将通过验证的XML文档。 I want a XML file containing all the possible nodes (at least once) the hierarchy of Classes/Properties can build.
我想要一个XML文件,其中包含所有可能的节点(至少一次),可以构建类/属性的层次结构。
A very reduced code example: 一个简化的代码示例:
[XmlRootAttribute]
[XmlTypeAttribute]
public class OrderType
{
public DeliveryType Delivery { get; set; }
//+ 50 more properties
public OrderType(){}
}
[XmlTypeAttribute]
public class DeliveryType
{
public QuantityType Quantity { get; set; }
//+ 10 more properties
public DeliveryType (){}
}
I have already tried to initialise some properties in some of the constructors and it works fine, but this method would take a whole week to finish. 我已经尝试在某些构造函数中初始化一些属性,并且可以正常工作,但是此方法将需要一整周的时间才能完成。
So! 所以! Is there a smart an quick method to generate a Mock XML document with all properties initialized?
有没有一种聪明的快速方法来生成所有属性都已初始化的Mock XML文档?
It's ok that the outer nodes just are defined eg: < Code /> 可以只定义外部节点,例如:<Code />
Well, sometimes you have to do it on your own: 好吧,有时候您必须自己做:
using System;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
namespace extanfjTest
{
class Program
{
static void Main(string[] args)
{
OrderType ouo = new OrderType(DateTime.Now);
SetProperty(ouo);
XmlSerializer ser = new XmlSerializer(typeof(OrderType));
FileStream fs = new FileStream("C:/Projects/group.xml", FileMode.Create);
ser.Serialize(fs, ouo);
fs.Close();
}
public static void SetProperty(object _object)
{
if (_object == null)
{ return; }
foreach (PropertyInfo prop in _object.GetType().GetProperties())
{
if ("SemlerServices.OIOUBL.dll" != prop.PropertyType.Module.Name)
{ continue; }
if (prop.PropertyType.IsArray)
{
var instance = Activator.CreateInstance(prop.PropertyType.GetElementType());
Array _array = Array.CreateInstance(prop.PropertyType.GetElementType(), 1);
_array.SetValue(instance, 0);
prop.SetValue(_object, _array, null);
SetProperty(instance);
}
else
{
var instance = Activator.CreateInstance(prop.PropertyType);
prop.SetValue(_object, instance, null);
SetProperty(instance);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.