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

白昼怎懂夜的黑 提交于 2019-12-11 14:22:23

问题


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


回答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



回答2:


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



来源:https://stackoverflow.com/questions/5498646/xml-object-reference-not-set-to-an-instance-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!