<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="~/" title="Úvodní stránka">
<siteMapNode url="Pocitace" title="Počítače" />
<siteMapNode url="Elektronika" title="Elektronika" />
</siteMapNode>
</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.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);
第51行si红色。你可以帮帮我吗?
(Web.sitemap我在根文件和代码中有Someting / Someting / Someting.aspx,所以我认为adrress是正确的。)
答案 0 :(得分:1)
对originalXml.SelectSingleNode("siteMapNode")
的调用会返回null
。您需要指定命名空间。
<强>更新强>
使用此代码而不是抛出异常的行(第51行):
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);
说明:
你犯了两个错误:
SelectSingleNode
答案 1 :(得分:0)
我认为,你给SelectSingleNode的xpath是错误的,它将以null返回。