John
John

Reputation: 135

XML: Object reference not set to an instance of an object

<?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

Answers (2)

Petike
Petike

Reputation: 1

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

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:

  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

Upvotes: 1

Related Questions