读取xml文件中节点

1、【在解决方案下新建Xml文件 并设置demo值】

2、【设置Xml文件属性为 始终复制】

3、【代码】

/// <summary>
        /// Xml文件名
        /// </summary>
        private const string _xmlFilePath = "XMLFileDemo.xml";
/// <summary>
        /// 获取Xml文件中节点的值
        /// </summary>
        /// <param name="value"></param>
        /// <param name="xmlPath">节点名称</param>
        /// <returns></returns>
        public static string GetPropertyValue(ref string value, string xmlPath)
        {
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(_xmlFilePath);
                XmlNodeList xmlNode = xml.SelectNodes(xmlPath);
                if (xmlNode.Count==0)
                {
                    throw new ApplicationException(string.Format("{0}文件中不存在节点{1}", _xmlFilePath, xmlPath));
                }
                value = xmlNode[0].InnerXml;
                return value;
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }
/// <summary>
        /// 更改Xml文件中某一节点的值
        /// </summary>
        /// <param name="value"></param>
        /// <param name="xmlPath"></param>
        public static void SetPropertyValue(string value, string xmlPath)
        {
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(_xmlFilePath);
                XmlNodeList xmlNode = xml.SelectNodes(xmlPath);
                if (xmlNode.Count == 0)
                {
                    throw new ApplicationException(string.Format("{0}文件中不存在节点{1}", _xmlFilePath, xmlPath));
                }
                xmlNode[0].InnerXml = value;
                xml.Save(_xmlFilePath);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }

4、【调用Demo】

public class Program
    {
        private string _myProperty;
        public string MyProperty {
            get
            {
                return SingleDemo.GetPropertyValue(ref _myProperty, "Settings/Name");
            }
            set {
                SingleDemo.SetPropertyValue(value, "Settings/Name");
            }
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p.MyProperty);
            Console.WriteLine("请输入变化后的值:");
            string s=Console.ReadLine();
            p.MyProperty = s;
            Console.WriteLine("变化后Property的值:"+p.MyProperty);
            Console.ReadLine();
        }
    }

 

原文地址:https://www.cnblogs.com/z-huan/p/7339403.html