2012-09-18 28 views
3

我嘗試(從Chirpy配置文件)解析這個XML文件:我的XPath有什麼問題?

<?xml version="1.0" encoding="utf-8" ?> 
<root xmlns="urn:ChirpyConfig" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="urn:ChirpyConfig http://www.weirdlover.com/chirpy/chirp.xsd"> 
    <FileGroup Name="Built.debug.js" Minify="false"> 
     <File Path="jquery/jquery-1.7.2.js"/> 
     <File Path="jquery.address/jquery.address-1.4.js" /> 
    </FileGroup> 
</root> 

與此代碼:

var path = Server.MapPath("~/Scripts/ScriptfilesMashup.chirp.config"); 
var file = new XPathDocument(path); 
var nav = file.CreateNavigator(); 
var nodes = nav.Select("/root/FileGroup/File"); 

nodes始終是空的,不管我如何調用該方法nav.Select。我之前幾乎沒有使用XPath,所以也許我做錯了 - 但是什麼?只有選擇器*給了我根節點。

選擇器會得到Path所有File節點的屬性是什麼?

編輯:解

感謝基里爾,最終的解決方案是這樣的:

var path = Server.MapPath("~/Scripts/ScriptfilesMashup.chirp.config"); 
var file = new XPathDocument(path); 
var nav = file.CreateNavigator(); 
var ns = "urn:ChirpyConfig"; 

XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable); 
nsMgr.AddNamespace("x", ns); 

var nodes = nav.Select("/x:root/x:FileGroup/x:File/@Path", nsMgr);  
while(nodes.MoveNext()) 
{ 
    var path = nodes.Current.Value; 
} 
+0

我在過去類似的問題,當我忽略了一個事實,即有涉及XML命名空間。請參閱[這個答案](http://stackoverflow.com/a/6635108/107625)作爲一個可能的提示我的問題。 –

回答

4

這是因爲元素rootFileGroupFileurn:ChirpyConfig命名空間中定義。

使用此:

XPathDocument xmldoc = new XPathDocument(xmlFile); 
XPathNavigator nav = xmldoc.CreateNavigator(); 
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable); 
nsMgr.AddNamespace("x", "urn:ChirpyConfig"); 
XPathNavigator result = nav.SelectSingleNode("/x:root/x:FileGroup/x:File", nsMgr); 
+0

非常感謝,我不知道它與名稱空間有關。但是你的代碼只給我一個節點,但我需要在一個字符串列表中包含所有'Path'屬性,我該怎麼做? – Marc

+0

@Marc,不客氣。使用'選擇'而不是'SelectSingleNode':http://msdn.microsoft.com/en-us/library/0ea193ac.aspx –

+0

是的,我試過了,但我發現我必須將XPath更改爲'/ x :根/ X:文件組/ X:文件/ @ Path'。再次感謝,我將發佈最終解決方案。 – Marc