简体   繁体   English

将XElement添加到XDocument时发生NullRefernceException

[英]NullRefernceException when adding XElement to a XDocument

I have the following .xml file: 我有以下.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>

Now, when I try to add another "Host" in the "RemoteHosts" section using the following code it raises a NullReferenceException: 现在,当我尝试使用以下代码在“ 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)));

anyway the 无论如何

xmlList.Save("NetConfig.xml");

works well, saving the new item...what's wrong? 工作正常,保存新项目...出了什么问题?

XmlList仅包含1个节点,其Params不是RemoteHosts

尝试xmlList.Root.Element("RemoteHosts")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM