C#使用反射得到屬性然后創建xml文檔


一:通過實體對象生成xml文檔

1.實體對象必須包含熟悉,且都是public類型,例如下面的person類

public  class Person 
{
public  string Id {  getset; } 
public  string Name {  getset; } 
public  string Age {  getset; } 
public  string Sex {  getset; } 
}

 

2.通過反射獲得熟悉名稱,並且轉換為小寫,同時使用System.Xml命名空間的相關類創建xml文檔

public  static  void CreateXmlByModel(List < object> list,  string filename,  string encode)
{
   string root = null ;
   if (list.Count >  0)
  {
   Type p = list[ 0].GetType();
   root = p.Name.ToLower() + " s ";
  }
  XmlDocument doc =  new XmlDocument();
  XmlDeclaration dec = doc.CreateXmlDeclaration( " 1.0 ", encode,  " yes ");
  doc.AppendChild(dec);
  XmlElement rootElement = doc.CreateElement(root);
  doc.AppendChild(rootElement);
   // 添加子節點 
   foreach( Object item  in list)
  {
    XmlElement e = doc.CreateElement(item.GetType().Name.ToLower());
    PropertyInfo[] pi = item.GetType().GetProperties();
     int i =  0;
     foreach ( PropertyInfo pro  in pi)
    {
     XmlElement child = doc.CreateElement(pro.Name.ToLower());
     child.InnerText = pro.GetValue(item,  null).ToString();
     e.AppendChild(child);
     i++;
    }
    rootElement.AppendChild(e);
  }
  doc.Save(filename);
}

 

二:根據xml文檔獲得實體的集合(實體是跟上面對應的)

public  static List<Person GetModelsFromXml(  string file)
{
   List<Person list =  null;
    if (File.Exists(file))
   {
     list =  new List<Person();
    // 解析xml
   XmlDocument doc =  new XmlDocument();
   doc.Load(file);
   Type type =  typeof(Person);
   String root = type.Name.ToLower() +  " s ";
   XmlNode rootNode = doc.SelectSingleNode(root);
   XmlNodeList nodes = rootNode.ChildNodes;
    foreach (XmlNode item  in nodes)
   {
    Person person =  new Person();
    PropertyInfo[] pi = type.GetProperties();
    XmlNodeList childs = item.ChildNodes;
     // 遍歷子節點 
     for (  int i =  0; i < childs.Count; i++)
    {
     XmlNode n = childs[i];
      // 查找屬性名稱和xml文檔中一致的節點名稱,並且設置屬性值
     List ps = pi.Where(p => p.Name.ToLower() == n.Name).ToList ();
     ps[ 0].SetValue(person, n.InnerText.ToString(),  null);
    }
   list.Add(person);
   }
  }
   return list;

} 

三:如果能將GetModelsFromXml方法再改造一下,適合多種實體,將里面的person變為object就perfect了,可是試了沒有成功,不知哪位大俠可以指點江山啊。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM