如何将对象转换为集合List <x>

时间:2016-10-19 08:55:11

标签: c# web-services .net-4.5.2

我有一个名为Gender的课程。我从web服务中读取数据,我需要将GenderObject转换为性别集合,即List _GenderList = object。

using (StreamReader _Reader = new StreamReader(_Stream))
  {
    GeneratedXPathString = _Reader.ReadToEnd();

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(GeneratedXPathString);

   string xmlcontents = doc.InnerXml;

    Object GenderObject = SystemCore.XMLPrasing.ObjectToXML(xmlcontents, typeof(Gender));

   //  List<Gender> GenderObject2 = ((IEnumerable<Gender>)GenderObject).Cast<Gender>().ToList(); //get error here

 }

性别等级

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

对象到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;
    }

调试模式中的GenderObject

enter image description here

XML文档

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

0 个答案:

没有答案