【问题标题】:XML: Object reference not set to an instance of an objectXML:对象引用未设置为对象的实例
【发布时间】:2011-03-31 10:49:24
【问题描述】:
<?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 号线是红色的。你能帮帮我吗?

(我在根文件中有 Web.sitemap,在 Someting/Someting/Someting.aspx 中有代码,所以我认为地址是正确的。)

【问题讨论】:

  • 显示异常堆栈跟踪
  • 请检查我的解决方案。它有效,我已经测试过了。

标签: c# asp.net xml sitemap


【解决方案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);

说明:
你犯了两个错误:

  1. 您查找 siteMapNode 的 XPath 查询不正确。你写它的方式,它只查看名称为“siteMapNode”的标签的根标签
  2. 根标签“siteMap”指定一个命名空间。您需要在调用 SelectSingleNode 时使用该命名空间

【讨论】:

  • 我使用此代码而不是第 51 行,现在我没有错误,但在 Web.sitemap 中不是新的 siteMapNode。 :-(
  • @John:因为您需要将 originalXml 中的 Xml 保存回磁盘 :)
  • 哦,originalXml.Save(Server.MapPath("../../Web.sitemap"));现在好了。谢谢 :-)
【解决方案2】:

我认为,你给 SelectSingleNode 的 xpath 是错误的,它会返回 null。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多