这个是和ALM上传测试结果结合使用的//把xml序列化成对象以及把对象序列化成xml using System; using System.Data; using System.Configuration; using System.Web; using System.IO; using System.Text; using System.Xml.Serialization; using System.Xml; namespace XMLUtils { /// <summary> /// Summary description for XMLUtils /// </summary> public class XMLUtils { public XMLUtils() { } public static String SerializedToXML(Type ObjectType_, object ObjectInstance_) { return SerializedToXMLStringBuilder(ObjectType_, ObjectInstance_).ToString(); } public static StringBuilder SerializedToXMLStringBuilder(Type ObjectType_, object ObjectInstance_) { StringBuilder sbXML = new StringBuilder(); XmlSerializer xs = new XmlSerializer(ObjectType_); xs.Serialize(new StringWriter(sbXML), ObjectInstance_); return sbXML; } public static object Deserialized(Type ObjectType_, string SerializedText_) { XmlSerializer xs = new XmlSerializer(ObjectType_); object oDeserialized = xs.Deserialize(new StringReader(SerializedText_)); return oDeserialized; } /// <summary> /// Serialize the object to stringbuilder. /// </summary> /// <param name="obj"></param> /// <param name="targetNamespace"></param> /// <returns></returns> public static StringBuilder SerializeObject(object obj, string targetNamespace) { System.Xml.Serialization.XmlSerializer ser; XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); if (string.IsNullOrEmpty(targetNamespace)) { ns.Add(string.Empty, string.Empty); } else { ns.Add("ns", targetNamespace); } ser = new System.Xml.Serialization.XmlSerializer(obj.GetType()); StringBuilder objectAsString = new StringBuilder(); StringWriter stringWriter = new StringWriter(objectAsString); XmlTextWriter writer = new XmlTextWriter(stringWriter); writer.Formatting = Formatting.None; ser.Serialize(writer, obj, ns); return objectAsString; } /// <summary> /// Deserialize the stringbuilder to object. /// </summary> /// <param name="objectType"></param> /// <param name="serializedXML"></param> /// <returns></returns> public static object DeserializeXML(Type objectType, StringBuilder serializedXML) { System.IO.StringReader reader = new System.IO.StringReader(serializedXML.ToString()); object deserializedObject = null; try { XmlSerializer xs = new XmlSerializer(objectType); System.Xml.XmlReader xr = System.Xml.XmlReader.Create(reader); deserializedObject = xs.Deserialize(xr); } catch (Exception) { } finally { if (reader != null) { reader.Dispose(); } } return deserializedObject; } } }
时间: 2024-11-05 14:46:42