首页 > 解决方案 > 使用 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.

标签: c#

解决方案


Element方法找到一个直接子元素。在您的情况下,您正在寻找DewesoftSetup,它在System其下DewesoftXML(它是根元素)。这里有两个选项:

首先,您可以使用Element两次 - 一次从根到System,然后再从SystemDewesoftSetup

doc.Root.Element("System").Element("DewesoftSetup").Add(root);

或者,您可以使用Descendants查找所有名为的后代DewesoftSetup,然后只取其中的第一个:

doc.Descendants("DewesoftSetup").First().Add(root);

我个人会使用第一种方法,但如果元素可以出现在多个不同的地方,则第二种方法会很有用。

顺便说一句,我会更改root变量的名称,因为这听起来像是您希望它是根元素,但事实并非如此。


推荐阅读