c#怎么在xml文件中追加内容
时间: 2024-02-03 08:13:45 浏览: 35
在 C# 中可以使用 XmlDocument 类来操作 XML 文件。要在 XML 文件中追加内容,可以按照以下步骤操作:
1. 加载 XML 文件到 XmlDocument 对象中:
```csharp
XmlDocument doc = new XmlDocument();
doc.Load("path/to/xml/file.xml");
```
2. 创建要添加到 XML 文件中的新元素,例如:
```csharp
XmlElement newElement = doc.CreateElement("newElement");
newElement.InnerText = "new element value";
```
3. 找到要将新元素添加到的现有元素,例如:
```csharp
XmlElement parentElement = doc.SelectSingleNode("//parentElement") as XmlElement;
```
4. 将新元素添加到现有元素中:
```csharp
parentElement.AppendChild(newElement);
```
5. 将更改保存回 XML 文件中:
```csharp
doc.Save("path/to/xml/file.xml");
```
完整的示例代码如下:
```csharp
XmlDocument doc = new XmlDocument();
doc.Load("path/to/xml/file.xml");
XmlElement newElement = doc.CreateElement("newElement");
newElement.InnerText = "new element value";
XmlElement parentElement = doc.SelectSingleNode("//parentElement") as XmlElement;
parentElement.AppendChild(newElement);
doc.Save("path/to/xml/file.xml");
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)