Reputation: 135
<?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>
And I write to this file new data:
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);
But I get:
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);
Line 51 si red. Can u help me?
(Web.sitemap i have in root file and code I have in Someting/Someting/Someting.aspx, so adrress is correct i think.)
Upvotes: 0
Views: 6834
Reputation: 1
I think, the xpath you give to the SelectSingleNode is wrong and it will return with null.
Upvotes: 0
Reputation: 174289
The call to originalXml.SelectSingleNode("siteMapNode")
returns null
. You need to specify the namespace.
Update:
Use this code instead of the line that throws the exception (Line 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);
Explanation:
You made two mistakes:
SelectSingleNode
Upvotes: 1