C# 读取和修改XML文件

一、读取XML信息

using System.Xml;  
/// <summary>
        /// 读取xml节点属性值
        /// setxml(xml路径,节点路径,节点属性名)
        /// </summary>
        public static string getxml(string xml, string node, string name)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xml);
            var root = xmlDoc.DocumentElement;//取到根结点
            XmlElement node1 = (XmlElement)xmlDoc.SelectSingleNode(node);
            return node1.GetAttribute(name).ToString();
        }

二、修改XML信息

using System.Xml;
 /// <summary>
        /// 修改xml节点属性值
        /// getxml(xml路径,节点路径,节点属性名,值)
        /// </summary>
        public static void setxml(string xml, string node, string name, string value)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xml);
            var root = xmlDoc.DocumentElement;//取到根结点
            XmlElement node1 = (XmlElement)xmlDoc.SelectSingleNode(node);
            node1.SetAttribute(name, value);
            xmlDoc.Save(xml);
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C#中操作XML文件需要使用System.Xml命名空间下的类。 以下是一个简单的示例,演示如何将数据写入XML文件并从中读取数据: ```csharp using System; using System.Xml; class Program { static void Main(string[] args) { // 创建XML文档对象 XmlDocument xmlDoc = new XmlDocument(); // 创建XML声明 XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); // 添加XML声明到XML文档 xmlDoc.AppendChild(xmlDec); // 创建根元素 XmlElement root = xmlDoc.CreateElement("students"); // 将根元素添加到XML文档 xmlDoc.AppendChild(root); // 创建子元素 XmlElement student = xmlDoc.CreateElement("student"); XmlAttribute id = xmlDoc.CreateAttribute("id"); id.Value = "001"; student.Attributes.Append(id); XmlElement name = xmlDoc.CreateElement("name"); name.InnerText = "Tom"; student.AppendChild(name); XmlElement age = xmlDoc.CreateElement("age"); age.InnerText = "18"; student.AppendChild(age); // 将子元素添加到根元素 root.AppendChild(student); // 保存XML文档 xmlDoc.Save("students.xml"); // 读取XML文档 xmlDoc.Load("students.xml"); // 获取根元素 root = xmlDoc.DocumentElement; // 遍历子元素 foreach (XmlElement ele in root.ChildNodes) { Console.WriteLine("Student ID: " + ele.Attributes["id"].Value); Console.WriteLine("Name: " + ele["name"].InnerText); Console.WriteLine("Age: " + ele["age"].InnerText); } Console.ReadLine(); } } ``` 上述代码将创建一个名为“students.xml”的XML文件,其中包含一个名为“students”的根元素和一个名为“student”的子元素。程序会将数据写入该文件,然后从文件中读取数据并将其打印出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lucky.帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值