0
<?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.)

John
  • 135
  • 2
  • 4
  • 12

2 Answers2

1

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:

  1. Your XPath query to find the siteMapNode was not correct. The way you wrote it, it looked only at the root tag for the tag with the name "siteMapNode"
  2. The root tag "siteMap" specifies a namespace. You need to use that namespace in your call to SelectSingleNode
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

I think, the xpath you give to the SelectSingleNode is wrong and it will return with null.

Petike
  • 1