要修改的页面是web.config页面。其中有一段这样的代码 我没有复制完
<!--邮件设置 -->
<SampEmailSender>
<default>
<add key="address" value="liuchao@db.org" />
<add key="name" value="liuchao" />
<add key="pwd" value="liuchao" />
<add key="host" value="10.0.4.208" />
<add key="port" value="25" />
</default>
<bjsasc.com>
<add key="address" value="liuchao@db.org" />
<add key="name" value="liuchao" />
<add key="pwd" value="liuchao" />
<add key="host" value="10.0.4.208" />
<add key="port" value="25" />
</bjsasc.com>
<db.org>
<add key="address" value="liuchao@db.org" />
<add key="name" value="liuchao" />
<add key="pwd" value="liuchao" />
<add key="host" value="10.0.4.208" />
<add key="port" value="25" />
</db.org>
</SampEmailSender>
<!--邮件设置 -->
要求是修改 SampEmailSender节点下的子节点 db.org 为dd.org、
并修改其内容
<add key="address" value="liuchao@db.org" />
<add key="name" value="liuchao" />
<add key="pwd" value="liuchao" />
<add key="host" value="10.0.4.208" />
<add key="port" value="25" />
为 <add key="address" value="liu@dd.org" />
<add key="name" value="liu" />
<add key="pwd" value="liu" />
<add key="host" value="10" />
<add key="port" value="2" />
--
string path = @"xml文件路径";
XElement x = XElement.Load(path);
x.Element("db.org").Remove();
XElement val = new XElement("dd.org",
new XElement("add", new XAttribute("key","address"),new XAttribute("value","liu@dd.org")),
new XElement("add", new XAttribute("key","name"),new XAttribute("value","liu")),
new XElement("add", new XAttribute("key","pwd"),new XAttribute("value","liu")),
new XElement("add", new XAttribute("key","host"),new XAttribute("value","10")),
new XElement("add", new XAttribute("key","post"),new XAttribute("value","2"))
);
x.Add(val);
x.Save(path);
提示:
未将对象引用设置到对象实例
@李小熊:
可能的原因:
一、你的XML文件路径错误
二、这个方法只能运行一次,如果已经删除了就会出错,你可以断点看一下
自己解决了。‘
因为<SampEmailSender> 不是根节点,所以上面方法中的x.Element("db.org")就找不到,返回Null.