C# XML:对象引用未设置为对象的实例
但我得到:C# XML:对象引用未设置为对象的实例,c#,asp.net,xml,sitemap,C#,Asp.net,Xml,Sitemap,但我得到: XmlDocument originalXml = new XmlDocument(); originalXml.Load(Server.MapPath("../../Web.sitemap")); XmlAttribute title = originalXml.CreateAttribute("title"); title.Value = newCategory; XmlAttribute url = originalXml.CreateAttribute("url"); url
XmlDocument originalXml = new XmlDocument();
originalXml.Load(Server.MapPath("../../Web.sitemap"));
XmlAttribute title = originalXml.CreateAttribute("title");
title.Value = newCategory;
XmlAttribute url = originalXml.CreateAttribute("url");
url.Value = seoCategory;
XmlNode newSub = originalXml.CreateNode(XmlNodeType.Element, "siteMapNode", null);
newSub.Attributes.Append(title);
newSub.Attributes.Append(url);
originalXml.SelectSingleNode("siteMapNode").AppendChild(newSub);
第51行是红色的。你能帮我吗
(我在根文件中有Web.sitemap,在Someting/Someting/Someting.aspx中有代码,所以我认为adress是正确的。)调用原始XML。选择SingleNode(“siteMapNode”)返回
null
。您需要指定名称空间
更新:使用此代码而不是引发异常的行(第51行): 说明:
你犯了两个错误:
SelectSingleNode
我认为,您给SelectSingleNode的xpath是错误的,它将返回null。显示异常堆栈跟踪。请检查我的解决方案。它可以工作,我已经测试过了。我使用了此代码而不是第51行,现在我没有错误,但在Web中。sitemap不是新的siteMapNode.:-(@John:因为您需要将originalXml中的Xml保存回磁盘:)噢,originalXml.save(Server.MapPath(“../../Web.sitemap”);现在一切都好了。Thx:-)
XmlDocument originalXml = new XmlDocument();
originalXml.Load(Server.MapPath("../../Web.sitemap"));
XmlAttribute title = originalXml.CreateAttribute("title");
title.Value = newCategory;
XmlAttribute url = originalXml.CreateAttribute("url");
url.Value = seoCategory;
XmlNode newSub = originalXml.CreateNode(XmlNodeType.Element, "siteMapNode", null);
newSub.Attributes.Append(title);
newSub.Attributes.Append(url);
originalXml.SelectSingleNode("siteMapNode").AppendChild(newSub);
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 49: newSub.Attributes.Append(title);
Line 50: newSub.Attributes.Append(url);
Line 51: originalXml.SelectSingleNode("siteMapNode").AppendChild(newSub);
XmlNamespaceManager nsmanager = new XmlNamespaceManager(originalXml.NameTable);
nsmanager.AddNamespace("x", "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0");
originalXml.SelectSingleNode("x:siteMap/x:siteMapNode", nsmanager).AppendChild(newSub);