2014-01-05 111 views
1

鑑於此XML,如何使用xpath查詢選擇PostBack的值?使用xpath選擇元素值

<AuthenticateResponse xmlns="http://example.com/authentication/response/1"> 
    <Status>success</Status> 
    <Result>more-info</Result> 
    <StateContext /> 
    <AuthenticationRequirements> 
    <PostBack>/Authentication/ExplicitForms/AuthenticateAttempt</PostBack> 
    <CancelPostBack>/Authentication/ExplicitForms/CancelAuthenticate</CancelPostBack> 
    <CancelButtonText>Cancel</CancelButtonText> 
    </AuthenticationRequirements> 
</AuthenticateResponse> 

我希望這個工作,但它返回null:

var nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("AuthenticateResponse", "http://example.com/authentication/response/1"); 
var node = doc.SelectSingleNode("//AuthenticateResponse:AuthenticationRequirements/PostBack", nsmgr); 

回答

1

你應該指定你的XPath都在提的每個元素的命名空間:

var nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("ns", "http://example.com/authentication/response/1"); 
var xpath = "/ns:AuthenticateResponse/ns:AuthenticationRequirements/ns:PostBack"; 
var node = doc.SelectSingleNode(xpath, nsmgr); 
+0

工程就像一個魅力,是否有鏈接文檔在哪裏解釋? – Remko

1

它應該是:

var node = doc.SelectSingleNode("/AuthenticateResponse:AuthenticateResponse/AuthenticateResponse:AuthenticationRequirements/AuthenticateResponse:PostBack", nsmgr); 
+1

正確的,謝爾蓋Berezovskiy稍快,所以我接受了一個 – Remko

+1

沒問題。他也不那麼冗長。 – Garett