XML:对象引用未设置为对象的实例 [英] XML: Object reference not set to an instance of an object

查看:155
本文介绍了XML:对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但是我得到了

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行为红色.你能帮我吗?

Line 51 si red. Can u help me?

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

(Web.sitemap i have in root file and code I have in Someting/Someting/Someting.aspx, so adrress is correct i think.)

推荐答案

originalXml.SelectSingleNode("siteMapNode")的调用返回 null .您需要指定名称空间.

The call to originalXml.SelectSingleNode("siteMapNode") returns null. You need to specify the namespace.

更新:
使用此代码,而不是引发异常的行(第51行):

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. 您的XPath查询以查找siteMapNode不正确.编写方式中,它仅查看名称为"siteMapNode"的标签的根标签
  2. 根标签"siteMap"指定一个名称空间.您需要在对 SelectSingleNode
  3. 的调用中使用该名称空间
  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

这篇关于XML:对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆