将xml反序列化为泛型类型

本文关键字:泛型类型 反序列化 xml | 更新日期: 2023-09-27 18:13:57

我需要一个有两个参数的类

1-类型==>类名2- XML字符串==>字符串格式的XML文档。

现在下面的类将xml转换为对象,这一切都很好,但我需要最终版本作为泛型类型

转换器类
public static partial class XMLPrasing
{
    public static Object ObjectToXML(string xml, Type objectType)
    {
        StringReader strReader = null;
        XmlSerializer serializer = null;
        XmlTextReader xmlReader = null;
        Object obj = null;
        try
        {
            strReader = new StringReader(xml);
            serializer = new XmlSerializer(objectType);
            xmlReader = new XmlTextReader(strReader);
            obj = serializer.Deserialize(xmlReader);
        }
        catch (Exception exp)
        {
            //Handle Exception Code
            var s = "d";
        }
        finally
        {
            if (xmlReader != null)
            {
                xmlReader.Close();
            }
            if (strReader != null)
            {
                strReader.Close();
            }
        }
        return obj;
    }
}

作为示例类

[Serializable]
[XmlRoot("Genders")]
public class Gender
{
    [XmlElement("Genders")]
    public List<GenderListWrap> GenderListWrap = new List<GenderListWrap>();       
}

public class GenderListWrap
{
    [XmlAttribute("list")]
    public string ListTag { get; set; }
    [XmlElement("Item")]
    public List<Item> GenderList = new List<Item>();
}

public class Item
{
    [XmlElement("CODE")]
    public string Code { get; set; }
    [XmlElement("DESCRIPTION")]
    public string Description { get; set; }
}

//

<Genders><Genders list='"1'">
<Item>
<CODE>M</CODE>
<DESCRIPTION>Male</DESCRIPTION></Item>
 <Item>
 <CODE>F</CODE>
 <DESCRIPTION>Female</DESCRIPTION>
 </Item></Genders>
 </Genders>

将xml反序列化为泛型类型

请看看我的解决方案是否对你有帮助。

下面是Method,它将xml转换为泛型类。

  public static T GetValue<T>(String value)
    {
        StringReader strReader = null;
        XmlSerializer serializer = null;
        XmlTextReader xmlReader = null;
        Object obj = null;
        try
        {
            strReader = new StringReader(value);
            serializer = new XmlSerializer(typeof(T));
            xmlReader = new XmlTextReader(strReader);
            obj = serializer.Deserialize(xmlReader);
        }
        catch (Exception exp)
        {
        }
        finally
        {
            if (xmlReader != null)
            {
                xmlReader.Close();
            }
            if (strReader != null)
            {
                strReader.Close();
            }
        }
        return (T)Convert.ChangeType(obj, typeof(T));
    }

如何调用该方法:

Req objreq = new Req();

objreq = GetValue (strXmlData);

Req是泛型类。strXmlData是xml字符串。

请求示例xml:

 <?xml version="1.0"?>
 <Req>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
  </Req>

请求类:

[System.SerializableAttribute()]
public partial class Req {
    [System.Xml.Serialization.XmlElementAttribute("book")]
    public catalogBook[] book { get; set; }
  }

[System.SerializableAttribute()]
public partial class catalogBook {
    public string author { get; set; }
    public string title { get; set; }
    public string genre { get; set; }
    public decimal price { get; set; }
    public System.DateTime publish_date { get; set; }
    public string description { get; set; }
    public string id { get; set; }
 }

在我的情况下,它是完美的工作,希望它将工作在你的例子。

谢谢。

如果你想用xml序列化和反序列化一个对象,这是最简单的方法:

要序列化和反序列化的类:

[Serializable]
public class Person()
{
   public int Id {get;set;}
   public string Name {get;set;}
   public DateTime Birth {get;set;}
}

将对象保存为xml:

public static void SaveObjectToXml<T>(T obj, string file) where T : class, new()
{
   if (string.IsNullOrWhiteSpace(file))
      throw new ArgumentNullException("File is empty");
   var serializer = new XmlSerializer(typeof(T));
   using (Stream fileStream = new FileStream(file, FileMode.Create))
   {
      using (XmlWriter xmlWriter = new XmlTextWriter(file, Encoding.UTF8))
      {
        serializer.Serialize(xmlWriter, obj);
      }
   }
}

从xml加载对象:

public static T LoadObjectFromXml<T>(string file) where T : class, new()
{
    if (string.IsNullOrWhiteSpace(file))
      throw new ArgumentNullException("File is empty");
    if (File.Exists(file))
    {
      XmlSerializer deserializer = new XmlSerializer(typeof(T));
      using (TextReader reader = new StreamReader(file))
      {
         obj = deserializer.Deserialize(reader) as T;
      }
    }
}

如何在Person类中使用这些方法:

Person testPerson = new Person {Id = 1, Name="TestPerson", Birth = DateTime.Now};
SaveObjectToXml(testPerson, string "C:''MyFolder");
//Do some other stuff
//Oh now we need to load the object
var myPerson = LoadObjectFromXml<Person>("C:''MyFolder");
Console.WriteLine(myPerson.Name); //TestPerson

Save和Load方法作用于所有类为[Serializable]且包含公共空构造函数的对象。