簡體   English   中英

將XElement添加到XDocument時發生NullRefernceException

[英]NullRefernceException when adding XElement to a XDocument

我有以下.xml文件:

<?xml version="1.0" encoding="utf-8" ?>
<Params>
  <Name>Resolver1</Name>
  <RemoteHosts>
    <Host>
      <Name>Locale</Name>
       <IP>localhost</IP>
       <Port>8082</Port>
     </Host>
  </RemoteHosts>
</Params>

現在,當我嘗試使用以下代碼在“ RemoteHosts”部分中添加另一個“主機”時,將引發NullReferenceException:

XDocument xmlList = XDocument.Load("NetConfig.xml");

xmlList.Element("RemoteHosts").Add(new XElement("Host",    
new XElement("Name", h.name),
new XElement("IP", h.IP),
new XElement("Port", h.port)));

無論如何

xmlList.Save("NetConfig.xml");

工作正常,保存新項目...出了什么問題?

XmlList僅包含1個節點,其Params不是RemoteHosts

嘗試xmlList.Root.Element("RemoteHosts")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM