2011-03-31 64 views
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> 

的一個實例,我對這個文件寫新的數據:XML:未將對象引用設置到對象

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 SI爲紅色。你能幫我嗎?

(Web.sitemap中我在根文件和代碼我在成才/成才/ Someting.aspx,所以adrress是正確的,我認爲。)

+0

顯示**異常堆棧跟蹤**。 – Aliostad 2011-03-31 10:53:16

+0

請檢查我的解決方案。它的工作原理,我測試過它。 – 2011-03-31 11:08:47

回答

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. 你的XPath查詢來查找siteMapNode是不正確的。您編寫它的方式,它只查看名稱爲「siteMapNode」的標記的根標記
  2. 根標記「siteMap」指定一個命名空間。你需要在你的調用中使用該命名空間SelectSingleNode
+0

我用這個代碼而不是51行,現在我沒有錯誤,但是在Web.sitemap中沒有新的siteMapNode。 :-( – John 2011-03-31 11:46:12

+0

@John:因爲你需要將original.xml中的Xml保存回磁盤:) – 2011-03-31 11:47:45

+0

哦,originalXml.Save(Server.MapPath(「../../ Web.sitemap」));現在可以了。 Thx :-) – John 2011-03-31 11:48:48

0

我認爲,你給SelectSingleNode的xpath是錯誤的,它將返回null。

相關問題