2011-06-19 108 views
0

我有以下.xml文件:NullRefernceException添加的XElement到的XDocument时

<?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> 

现在,当我尝试使用下面的代码它提出了一个NullReferenceException的“RemoteHosts”一节中再添“主机” :

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"); 

效果很好,节约了新项目......什么是错的?

+0

可以调试,找出实际上是空?它是h变量还是“RemoteHosts”节点?不清楚。 –

+0

您保存的文件是否包含新的“主机”节点? –

+0

@ek_ny xmlList.Element(“RemoteHosts”)为空.. – Rick

回答

1

XMLList包含只有1个节点及其ParamsRemoteHosts

+0

谢谢!现在使用xmlList.Element(“Params”)。Element(“RemoteHosts”)。添加...它的工作原理! – Rick

0

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