在C#中使用XmlDocument类可以很方便地操作XML。以下是一些常见的用法:
- 创建一个XmlDocument对象:
XmlDocument xmlDoc = new XmlDocument();
- 加载一个XML文档:
xmlDoc.Load("path/to/xml/file.xml");
- 创建一个XML文档:
xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement rootElement = xmlDoc.CreateElement("Root"); xmlDoc.AppendChild(rootElement);
- 获取XML文档的根节点:
XmlElement rootElement = xmlDoc.DocumentElement;
- 查找XML文档中的节点:
XmlNodeList nodeList = xmlDoc.SelectNodes("//NodeName"); foreach (XmlNode node in nodeList) { // 处理节点 }
- 获取节点的属性:
string attributeValue = https://www.yisu.com/ask/node.Attributes["AttributeName"].Value;
- 创建一个新节点:
XmlElement newNode = xmlDoc.CreateElement("NewNode");
- 在父节点下添加子节点:
parentNode.AppendChild(newNode);
- 修改节点的属性值:
node.Attributes["AttributeName"].Value = "https://www.yisu.com/ask/NewValue";
- 删除节点:
parentNode.RemoveChild(node);
- 保存XML文档:
xmlDoc.Save("path/to/save/xml/file.xml");
以上是一些常见的XmlDocument的用法,你可以根据具体的需求进行操作。