using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.IO; namespace FileManager { public class XmlManager { #region 创建Xml文件,并创建根节点和属性 /// /// 创建Xml文件,并创建根节点和属性 /// /// Xml文件的全路径 /// 根节点名 /// 根节点的属性键值对 /// public Boolean CreateXmlFile(String xmlfullname,String rootnode,List> list_attributes) { XmlDocument xmlDoc = new XmlDocument(); //创建类型声明节点 XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", ""); xmlDoc.AppendChild(node); //创建根节点 XmlNode root = xmlDoc.CreateElement(rootnode); xmlDoc.AppendChild(root); //为根节点增加属性 for (int i = 0; i < list_attributes.Count; i++) { XmlNode attribute = xmlDoc.CreateNode(XmlNodeType.Attribute, list_attributes[i].Key, null); attribute.Value = list_attributes[i].Value; root.Attributes.SetNamedItem(attribute); } try { xmlDoc.Save(xmlfullname); return true; } catch (Exception e) { //显示错误信息 Console.WriteLine(e.Message); return false; } } #endregion #region 创建节点或子节点 /// /// 创建节点或子节点 /// /// xml文档 /// 父节点 /// 节点名 /// 节点值 /// 节点属性 public Boolean CreateNode(String xmlfullname, String parentNode, string name, string value, List> list_attributes) { if(!File.Exists(xmlfullname) || name.Trim()=="" || parentNode.Trim()=="") { return false; } XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlfullname); XmlNode root = xmlDoc.SelectSingleNode(parentNode); XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null); //为根节点增加属性 for (int i = 0; i < list_attributes.Count; i++) { XmlNode attribute = xmlDoc.CreateNode(XmlNodeType.Attribute, list_attributes[i].Key, null); attribute.Value = list_attributes[i].Value; node.Attributes.SetNamedItem(attribute); } if (value.Trim() != "") { node.InnerText = value; } root.AppendChild(node); xmlDoc.Save(xmlfullname); return true; } catch(Exception e) { return false; } } #endregion } }