C# 使用C在现有XML中添加元素#
我试图使用XDocument将元素添加到现有的XML文档中。我得到一个空引用异常,因为它找不到我要附加的元素 代码如下:C# 使用C在现有XML中添加元素#,c#,C#,我试图使用XDocument将元素添加到现有的XML文档中。我得到一个空引用异常,因为它找不到我要附加的元素 代码如下: XDocument doc = XDocument.Load(@"C:\Documents\Test.xml"); XElement root = new XElement("SystemMonitor"); doc.Element("DewesoftSetup").Add(root);
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
下,它本身位于DewesoftXML
下(它是根元素)。这里有两个选项:
首先,您可以使用元素
两次-一次从根目录到系统
,然后再次从系统
到DewesoftSetup
:
doc.Root.Element(“System”).Element(“DewesoftSetup”).Add(Root);
或者,您可以使用子体
查找所有名为DewesoftSetup
的子体,然后只取第一个:
doc.substands(“DewesoftSetup”).First().Add(root);
就我个人而言,我会使用第一种方法,但是如果元素可以出现在多个不同的地方,第二种方法会很有用
顺便说一句,我会更改
根变量的名称,因为它听起来像是您希望它是根元素,而实际上不是。啊,谢谢!我知道我错过了一些简单的事情
System.Xml.Linq.XContainer.Element(...) returned null.