c# - 使用 C# 在现有 XML 中添加元素
问题描述
我正在尝试使用 XDocument 将元素添加到现有 XML 文档中。我得到一个空引用异常,因为它没有找到我要附加的元素。
这是代码:
XDocument doc = XDocument.Load(@"C:\Documents\Test.xml");
XElement root = new XElement("SystemMonitor");
doc.Element("DewesoftSetup").Add(root);
doc.Save(@"C:\Documents\Test.xml");
这是 XML:
<?xml version="1.0" encoding="utf-8"?>
<DewesoftXML>
<System Name="Local">
<SysInfo>
</SysInfo>
<DewesoftSetup>
</DewesoftSetup>
</System>
</DewesoftXML>
我正在尝试向 DewesoftSetup 添加一个子元素。
继承人的错误:
System.Xml.Linq.XContainer.Element(...) returned null.
解决方案
该Element
方法找到一个直接子元素。在您的情况下,您正在寻找DewesoftSetup
,它在System
其下DewesoftXML
(它是根元素)。这里有两个选项:
首先,您可以使用Element
两次 - 一次从根到System
,然后再从System
到DewesoftSetup
:
doc.Root.Element("System").Element("DewesoftSetup").Add(root);
或者,您可以使用Descendants
查找所有名为的后代DewesoftSetup
,然后只取其中的第一个:
doc.Descendants("DewesoftSetup").First().Add(root);
我个人会使用第一种方法,但如果元素可以出现在多个不同的地方,则第二种方法会很有用。
顺便说一句,我会更改root
变量的名称,因为这听起来像是您希望它是根元素,但事实并非如此。
推荐阅读
- java - 在后台 java 控制台应用程序上打印字母 X
- sql - 在 postgresql 查询中需要拆分行的帮助
- kubernetes - 在 Helm 图表中编写自定义函数
- css - 导航选项卡上的 CSS 形状
- ubuntu-16.04 - 无法在 Ubuntu 服务器上安装 docker
- redux - 不可变 JS:更新嵌套的动态对象
- php - 如何使用 laravel 5.4 使用 cartalyst sentinel 发送激活电子邮件/代码
- c# - 如何在 ASP.NET MVC5 Razor 语法中向 SelectListItem 添加类?
- postgresql - 有没有办法将时间戳转换为纪元毫秒
- mysql - phpmyadmin 在侧边栏中显示表格,但表格不存在