我有以下.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");
效果很好,节约了新项目......什么是错的?
可以调试,找出实际上是空?它是h变量还是“RemoteHosts”节点?不清楚。 –
您保存的文件是否包含新的“主机”节点? –
@ek_ny xmlList.Element(“RemoteHosts”)为空.. – Rick