2011-03-31 5 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시 빨간색으로. 나를 도와 주실 수있으세요?

은 (Web.sitemap 내가 루트 파일 내가가 someting /가 someting/Someting.aspx에있는 코드에서, 그래서 adrress 내가 생각하는 올바른 것입니다.)

+0

** 예외 스택 추적 ** 표시. – Aliostad

+0

내 해결책을 확인하십시오. 그것은 작동, 나는 그것을 테스트했습니다. –

답변

1

호출 originalXml.SelectSingleNode("siteMapNode")로 돌아 null. 네임 스페이스를 지정해야합니다.

업데이트 :
사용하는 대신 예외를 throw 줄의 코드 (라인 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에주는 XPath는 잘못, SelectSingleNode
+0

나는이 코드를 51 행 대신에 사용했지만 이제 오류가 없지만 Web.sitemap에는 새로운 siteMapNode가 없다. :-( – John

+0

@ 존 : Xml을 originalXml 안에 디스크에 다시 저장해야하기 때문에 :) –

+0

오, originalXml.Save (Server.MapPath ("../../ Web.sitemap")); 그리고 지금 ok. Thx :-) – John

0

내 생각에 당신의 전화에서 해당 네임 스페이스를 사용할 필요는 null를 돌려줍니다.

관련 문제