对象与XML的互相转化,大家可以试下
如果用XMLSerializer不行的话,可以试试这个。比较适合比较小的对象,数据量大或者结构复杂的要慎用。测试下有什么问题。
========================================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Collections;
namespace System
{
public static class XMLConvert
{
private const string tag_reference = "ref";
private const string tag_type = "type";
private const string tag_param = "params";
private const char char_left = '(';
private const char char_right = ')';
private static Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
public static string ToXML(object o)
{
return ToXML("class", o);
}
public static string ToXML(string name, object o)
{
StringBuilder stringBuilder = new StringBuilder();
XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(stringBuilder));
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
ToXML(name, o, xmlWriter, new Hashtable());
xmlWriter.WriteEndDocument();
return stringBuilder.ToString();
}
public static object ToObject(string strXML)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(strXML);
return ToObject(xml);
}
public static object ToObject(XmlDocument xml)
{
Hashtable refMap = new Hashtable(xml.ChildNodes.Count * 4);
object value = ToObject(xml.LastChild, refMap);
return value;
}
private static void ToXML(string name, object value, XmlWriter xmlWriter, Hashtable refMap)
{
xmlWriter.WriteStartElement(name);
if (value != null)
{
if (refMap.ContainsKey(new Ref(value)))
{
xmlWriter.WriteAttributeString(tag_reference, refMap[new Ref(value)].ToString());
}
else
{
Type type = value.GetType();
TypeToXML(type, xmlWriter);
if (!type.IsValueType)
{
xmlWriter.WriteAttributeString(tag_reference, refMap.Count.ToString());
refMap.Add(new Ref(value), refMap.Count);
}
if (type.IsPrimitive || type.Equals(typeof(string)))
{
xmlWriter.WriteString(Convert.ToString(value));
}
else if (type.IsArray)
{
foreach (object subvalue in (value as Array))
{
ToXML("element", subvalue, xmlWriter, refMap);
}
}
else
{
ToXML(type, value, xmlWriter, refMap);
}
}
}
xmlWriter.WriteEndElement();
}