通用类选择Xml中的元素值到类的属性

时间:2012-01-20 06:22:03

标签: c# xml linq generics

我有一个xml,如:

<?xml version="1.0" encoding="utf-8" ?>
<Property>
  <Owner>
    <FirstName>LeBron</FirstName>
    <LastName>James</LastName>
  </Owner>
  <Seller>
    <Name>LeBron</Name>
    <Code>Seller01</Code>
    <Branch>demoBranch</Branch>
  </Seller>
  <Equipments>
      <Equipment>
        <Name>Kodle</Name>
        <CountryOfOrigin>Bryant</CountryOfOrigin>
      </Equipment>
      <Equipment>
        <Name>Desktop</Name>
        <CountryOfOrigin>Kryon</CountryOfOrigin>
      </Equipment>
    </Equipments>
</Property>

和班级:

public Property()
{
    public Owner owner{get;set;}
    public Seller seller{get;set;}
    public equipment equipment{get;set;}
}

public Owner
{
    public FirstName{get;set;}
    public LastName{get;set;}
}
public Seller
{
    public Name{get;set;}
    public Code{get;set;}
    public Branch{get;set;}
}
public Equipment
{
    public Name{get;set;}
    public CountryOfOrigin{get;set;}
}

当然,我们可以逐个从xml加载类,如:

    XDocument xDoc = XDocument.Load(xmlFile);     

    var owner = from e in doc.Descendants("Owner")
                select new Owner
                {
                    FirstName = e.Element("FirstName").Value,
                    LastName = e.Element("LastName").Value
                };   

或反序列化xml并获取子类。

    public Property LoadFromDocument(string fileUrl){
        Property serializableObject = null;
         using(TextReader textReader = textReader = new StreamReader(fileUrl)){
             XmlSerializer xmlSerializer = new XmlSerializer(ObjectType);
             serializableObject = xmlSerializer.Deserialize(textReader) as Property;
        }
        return serializableObject;
    }

然后通过

获得所有者
Owner owner = LoadFromDocument(filrUrl).Owner;

但我想创建一个类似于下面的泛型类。

public class OXmlRepository<T>
{

    public XDocument xDoc { get; set; }
     protected XName ElementName { get; private set; }
     protected OXmlRepository()
    {
        ElementName = typeof(T).Name.ToString();
    }

    public T GetObject()
    {
            //how can I get the class T instance with the values from Xml
    }

}

1 个答案:

答案 0 :(得分:2)

public T GetObject()
{
    var xs = new XmlSerializer(typeof(T));
    using(var reader = xDoc.CreateReader())
    {
        return (T)xs.Deserialize(reader);
    }
}