将xml反序列化为Generic类型

时间:2016-10-19 09:51:41

标签: c# xml-deserialization .net-4.5.2

我需要带两个参数的类

1- Type ==>班级名称 2- xml string ==>字符串格式的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>

2 个答案:

答案 0 :(得分:3)

请检查我的解决方案是否对您有帮助。

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

 <?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>

如何调用该方法:

Req objreq = new Req();

objreq = GetValue(strXmlData);

Req是Generic Class。 strXmlData是xml字符串。

请求样本xml:

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

 }

请求类:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Live</title>
  <link rel="stylesheet" type="text/css" href="video-js.css">
  <script src="video.js"></script>
  <script>
    videojs.options.flash.swf = "video-js.swf";
  </script>
</head>
<body>
 <center>
   <video id="livestream" class="video-js vjs-default-skin vjs-big-play-centered"
     controls autoplay preload="auto" width="1280" height="720"
     data-setup='{"example_option":true}'>
      <source src="rtmp://192.168.32.15:1935/live/myStream" type="rtmp/mp4">
   </video>
 </center>
</body>
</html>

在我的情况下它完美运行,希望它能在你的例子中起作用。

谢谢。

答案 1 :(得分:1)

如果你想用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

保存和加载方法正在处理每个对象,该类是[Serializable]并且包含公共空构造函数。