Linux 拨号vps windows公众号手机端

C#中XML操作类怎么使用

lewis 8年前 (2017-12-24) 阅读数 7 #程序编程
文章标签 c#XML

在C#中,可以使用System.Xml命名空间中的类来操作XML。下面是一个简单的示例,演示了如何创建XML文档、添加元素、保存和读取XML文档。

首先,需要引入System.Xml命名空间:

using System.Xml;
  1. 创建XML文档:
XmlDocument xmlDoc = new XmlDocument();
  1. 添加根元素:
XmlElement root = xmlDoc.CreateElement("Root");
xmlDoc.AppendChild(root);
  1. 添加子元素:
XmlElement child = xmlDoc.CreateElement("Child");
child.InnerText = "Hello World";
root.AppendChild(child);
  1. 保存XML文档:
xmlDoc.Save("path/to/file.xml");
  1. 读取XML文档:
xmlDoc.Load("path/to/file.xml");

XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Child");
foreach (XmlNode node in nodeList)
{
    string text = node.InnerText;
    Console.WriteLine(text);
}

这只是一个简单的示例,System.Xml命名空间还提供了更多的类和方法来处理XML文档,如XmlReader和XmlWriter等。可以根据具体需求进一步学习和使用。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门