我試圖獲取下面XML結構中的<d:neu_UniqueId>
和<d:Name>
元素的值。我正在處理的程序調用WCF Web服務,並根據用戶輸入的搜索條件返回一個包含此信息列表的XML文檔(我已經刪除了隱私值)。C#XML解析錯誤:未將對象引用設置爲對象實例
<entry>
<id xmlns=\"http://www.w3.org/2005/Atom\">http://quahildy01/xRMDRMA02/XRMServices/2011/OrganizationData.svc</id>
<title type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\">somethingHere</title>
<updated xmlns=\"http://www.w3.org/2005/Atom\">2013-04-24T17:15:45Z</updated>
<author xmlns=\"http://www.w3.org/2005/Atom\"><name /></author>
<link rel=\"edit\" title=\"Account\" href=\"AccountSet(guid'aa2232f4-418a-e111-9710-005056a8161c')\" xmlns=\"http://www.w3.org/2005/Atom\" />
<category term=\"Microsoft.Crm.Sdk.Data.Services.Account\" scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" xmlns=\"http://www.w3.org/2005/Atom\" />
<content type=\"application/xml\" xmlns=\"http://www.w3.org/2005/Atom\">
<m:properties xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">
<d:neu_UniqueId xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\">123</d:neu_UniqueId>
<d:AccountId m:type=\"Edm.Guid\" xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\">1</d:AccountId>
<d:Name xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\">SomethingInHere</d:Name>
</m:properties>
</content>
</entry>
這是我正在使用的C#代碼。當我通過代碼,我可以看到正確的值在childNode
變量,然而,當在所述第一.InnerText()
方法的程序I移動接收到此錯誤:
NullReferenceException: Object reference not set to an instance of an object.
這裏是代碼
try
{
WebRequest myWebRequest = WebRequest.Create(URL);
myWebRequest.PreAuthenticate = true;
myWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream myFileStreamResult = myWebResponse.GetResponseStream();
Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(myFileStreamResult, encoder);
results = readStream.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(results);
XmlNodeList parentNode = xmlDoc.GetElementsByTagName("entry");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
nsmgr.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
string accountName2 = xmlDoc.SelectSingleNode("entry/content/m:properties/d:Name", nsmgr).InnerText;
foreach (XmlNode childNode in parentNode)
{
string accountName = childNode.SelectSingleNode("/content/m:properties/d:Name", nsmgr).InnerText;
string uniqueId = childNode.SelectSingleNode("/content/m:properties/d:neu_UniqueId", nsmgr).InnerText;
}
}
編輯
看起來像這是從Web服務返回XML的問題。對於每個元素,xmlns
屬性包含值前的\
字符。
我認爲你'childNode.SelectSingleNode()'語句沒有真正找到節點 – 2013-04-24 20:34:37
我同意,但我不明白爲什麼。我相信我已經設置了命名空間並正確地調用了路徑。這是我第一次解析XML,但是,所以我可能是錯的。 – NealR 2013-04-24 20:37:04
我個人沒有太多處理XML命名空間的經驗,但我認爲這可能是問題所在。這是我想看的一件事 – 2013-04-24 20:38:09