一:通过实体对象生成xml文档
1.实体对象必须包含熟悉,且都是public类型,例如下面的person类
public class Person { public string Id { get; set; } public string Name { get; set; } public string Age { get; set; } public string Sex { get; set; } }
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;
}