C# 创建 读取 更新 XML文件

public static class XmlHelper
    {
        /// <summary>
        /// 读取节点值
        /// </summary>
        /// <param name="Path">XML文件路径</param>
        /// <param name="Node1">第一级节点</param>
        /// <param name="Node2">第二级节点</param>
        /// <returns></returns>
        public static string GetXmlReader(string Path, string Node1, string Node2)
        {
            XmlDocument myDc = new XmlDocument();
            myDc.Load(Path);
            return myDc.SelectSingleNode(Node1).SelectSingleNode(Node2).InnerText;
        }


        /// <summary>
        /// 创建一个XML文件
        /// </summary>
        /// <param name="Path">XML文件路径</param>
        /// <param name="key">List</param>
        /// <param name="value">List</param>
        public static void CreateXML(string Path, List<string> key, List<string> value)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(node);
            XmlNode root = xmlDoc.CreateElement("Config");
            xmlDoc.AppendChild(root);

            for (int i = 0; i < key.Count; i++)
            {
                CreateNode(xmlDoc, root, key[i].ToString(), value[i].ToString());
            }
            try
            {
                xmlDoc.Save(Path);
            }
            catch (Exception e)
            {
            }
        }


        /// <summary>
        /// 创建一个XML文件中的 节点
        /// </summary>
        /// <param name="xmlDoc"></param>
        /// <param name="parentNode"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }


        /// <summary>
        /// 更新XML中指定节点的值
        /// </summary>
        /// <param name="Path">XML文件路径</param>
        /// <param name="NodeName">需要更改的节点</param>
        /// <param name="NodeValue">需要更新的节点值</param>
        public static void UpdateNode(string Path, string NodeName, string NodeValue)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Path);
            XmlNode xn = doc.SelectSingleNode("//" + NodeName + "");
            xn.InnerText = NodeValue;
            doc.Save(Path);
        }

    }

 

上一篇:如何健壮你的后端服务?


下一篇:oc-09-#pragma mark指令的使用,用于查找代码