也許不是最好的方式,但它爲我工作。 我創建了一個序列化的方法。
使用
VAR XML = Util.ObjetoToXML(OBJ,NULL,NULL).OuterXml;
方法
public static XmlDocument ObjetoToXML(object obj, XmlDocument xmlDocument, XmlNode rootNode)
{
if (xmlDocument == null)
xmlDocument = new XmlDocument();
if (obj == null) return xmlDocument;
Type type = obj.GetType();
if (rootNode == null) {
rootNode = xmlDocument.CreateElement(string.Empty, type.Name, string.Empty);
xmlDocument.AppendChild(rootNode);
}
if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String) || type == typeof(DateTime))
{
// Simples types
if (obj != null)
rootNode.InnerText = obj.ToString();
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
// Genericis types
XmlNode node = null;
foreach (var item in (IEnumerable)obj)
{
if (node == null)
{
node = xmlDocument.CreateElement(string.Empty, item.GetType().Name, string.Empty);
node = rootNode.AppendChild(node);
}
ObjetoToXML(item, xmlDocument, node);
}
}
else
{
// Classes types
foreach (var propertie in obj.GetType().GetProperties())
{
XmlNode node = xmlDocument.CreateElement(string.Empty, propertie.Name, string.Empty);
node = rootNode.AppendChild(node);
var valor = propertie.GetValue(obj, null);
ObjetoToXML(valor, xmlDocument, node);
}
}
return xmlDocument;
}
你可以用一個具體實現IEnumerable的,如清單更換方法定義? –
2012-02-01 19:51:39
[使用WCF,LINQ,JSON時無法序列化'System.Linq.Enumerable ...'類型的參數的可能的重複](http://stackoverflow.com/questions/2068897/cannot-serialize-parameter-of-type -system-linq-enumerable-when-using-wcf) – Coincoin 2012-02-01 19:52:33
[Serialize Objects using xmlSerializer。序列化和IEnumerable對象](http://stackoverflow.com/questions/2729875/serialize-objects-using-xmlserializer-serialize-and-ienumerable-objects) – 2012-02-01 19:52:47