csharp 创建xml文件并读取节点
时间: 2024-01-31 22:03:29 浏览: 36
创建xml文件:
```csharp
using System.Xml;
// 创建XmlDocument对象
XmlDocument xmlDoc = new XmlDocument();
// 创建XmlDeclaration对象
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
// 添加XmlDeclaration对象到XmlDocument对象中
xmlDoc.AppendChild(xmlDeclaration);
// 创建根节点
XmlNode rootNode = xmlDoc.CreateElement("Root");
// 添加根节点到XmlDocument对象中
xmlDoc.AppendChild(rootNode);
// 创建子节点
XmlNode childNode = xmlDoc.CreateElement("Child");
// 设置子节点属性
XmlAttribute attribute = xmlDoc.CreateAttribute("Name");
attribute.Value = "Child1";
childNode.Attributes.Append(attribute);
// 添加子节点到根节点中
rootNode.AppendChild(childNode);
// 保存XmlDocument对象到文件中
xmlDoc.Save("test.xml");
```
读取节点:
```csharp
using System.Xml;
// 加载XmlDocument对象
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("test.xml");
// 获取根节点
XmlNode rootNode = xmlDoc.SelectSingleNode("Root");
// 获取所有子节点
XmlNodeList childNodes = rootNode.ChildNodes;
// 遍历所有子节点
foreach (XmlNode childNode in childNodes)
{
// 获取子节点属性
XmlAttribute attribute = childNode.Attributes["Name"];
if (attribute != null)
{
string name = attribute.Value;
Console.WriteLine(name);
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)