2011-03-30 92 views
3

我知道這個問題已被問過類似的方式,但我似乎無法得到這個工作。SelectSingleNode返回null - 即使與命名空間

我有一些XML:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
    <Research xmlns="http://www.rixml.org/2005/3/RIXML" xmlns:xalan="http://xml.apache.org/xalan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" createDateTime="2011-03-29T15:41:48Z" language="eng" researchID="MusiJvs3008"> 
    <Product productID="MusiJvs3008"> 
    <StatusInfo currentStatusIndicator="Yes" statusDateTime="2011-03-29T15:41:48Z" statusType="Published" /> 
    <Source> 
    <Organization type="SellSideFirm" primaryIndicator="Yes"> 
    <OrganizationID idType="Reuters">9999</OrganizationID> 

我試圖使用XPath讀取值:

XPathDocument xmldoc = new XPathDocument(xmlFile); 
XPathNavigator nav = xmldoc.CreateNavigator(); 
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable); 
nsMgr.AddNamespace(string.Empty, "http://www.rixml.org/2005/3/RIXML"); 
XPathNavigator result = nav.SelectSingleNode("/Research", nsMgr); // <-- Returns null! 

但即使是一個簡單的選擇根節點的返回null!我確定我的名字空間有問題。有人可以幫忙嗎?

理想我想簡單的線條,讓我從XML文件中選擇值,即

String a = xmlDoc.SelectSingleNode(@"/Research/Product/Content/Title").Value; 

順便說一句,我沒有對XML文件的內容不(直接)的控制。

回答

5

我不相信你可以使用一個空的名稱空間別名,並讓它由XPath表達式自動使用。只要你使用一個實際的別名,它應該儘管工作。這個測試是好的,例如:

using System; 
using System.Xml; 
using System.Xml.XPath; 

class Test 
{ 
    static void Main() 
    { 
     string xmlFile = "test.xml"; 
     XPathDocument xmldoc = new XPathDocument(xmlFile); 
     XPathNavigator nav = xmldoc.CreateNavigator(); 
     XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable); 
     nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML"); 
     XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr); 
     Console.WriteLine(result); 
    } 
} 

的方式使用XPath和XPathDocument,?我傾向於發現LINQ to XML是一個更令人愉快的API,特別是當涉及到命名空間時。如果你使用的是.NET 3.5,並且你沒有特別的要求使用XPath,我建議你檢查一下。

+0

很好的答案,非常感謝您的幫助。我很想使用LINQ,但是我對調試的影響感到惱火,即任何對lamda表達式的改變意味着您必須重新啓動整個過程。再次感謝! Ryan – Ryan 2011-03-30 17:01:19

+0

@Ryan:你在調試器中花了很多時間嗎?我很少使用編輯並繼續 - 我只是重新編譯並再次運行單元測試。 – 2011-03-30 17:04:10

+0

永遠!我發現停止/啓動開發非常緩慢,特別是如果它是一個ASP應用程序。 – Ryan 2011-04-05 06:51:03

3

做如下修改

nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML"); 
XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr); 
0

我可以發佈,並回答我的問題,爲本地相當於該代碼。相反,我只是將它添加爲結尾的答案。

當使用本地IXMLDOMDocument(第6版)對象:

//Give the default namespace as alias of "x" 
document.setProperty("SelectionNamespaces","xmlns:x='http://www.rixml.org/2005/3/RIXML'"); 

//Query for the nodes we want 
document.selectSingleNode("/x:Research"); 

獎勵題:爲什麼,爲什麼,它的時候不指定XML文檔對象模型查詢默認名字空間中沒有命名空間。 .. 嘆息