在C#中,可以使用System.Xml命名空间中的类来操作XML。下面是一个简单的示例,演示了如何创建XML文档、添加元素、保存和读取XML文档。
首先,需要引入System.Xml命名空间:
using System.Xml;创建XML文档:XmlDocument xmlDoc = new XmlDocument();添加根元素:XmlElement root = xmlDoc.CreateElement("Root");xmlDoc.AppendChild(root);添加子元素:XmlElement child = xmlDoc.CreateElement("Child");child.InnerText = "Hello World";root.AppendChild(child);保存XML文档:xmlDoc.Save("path/to/file.xml");读取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等。可以根据具体需求进一步学习和使用。

