使用xpath选择元素值

时间:2014-01-05 21:04:35

标签: c# .net xml xpath

鉴于此XML,如何使用xpath查询选择PostBack的值?

<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);

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

应该是:

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