将 xml 反序列化为通用类型

Deserialize xml to Generic type

我需要 class 需要两个参数

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

现在跟随 class 将 xml 转换为对象,一切正常,但我需要最终版本作为通用类型

转换器class

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;
    }

}

示例class

[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序列化和反序列化一个对象,这是最简单的方法:

我们要序列化和反序列化的class:

[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 class:

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

保存和加载方法适用于 class 是 [Serializable] 且包含 public 个空构造函数的每个对象。

如果对你有帮助,请查看我的解决方案。

下面是将 xml 转换为通用 Class 的方法。

  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);

请求是通用的 Class。 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>

请求Class:

[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; }

 }

在我的例子中它工作得很好,希望它能在你的例子中工作。

谢谢。