[英]Adding Elements in an existing XML using C#
我正在嘗試使用 XDocument 將元素添加到現有的 XML 文檔中。 我收到 null 引用異常,因為它沒有找到我想要的元素 append。
這是代碼:
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
變量的名稱,因為這聽起來像是您希望它是根元素,但事實並非如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.