1
我有一個XML這樣的:泛型類選擇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
}
}