Remko
Remko

Reputation: 7340

Select element value with xpath

Given this XML, how to select the value of PostBack using xpath query?

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

I would expect this to work but it returns null:

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

Upvotes: 1

Views: 348

Answers (2)

Garett
Garett

Reputation: 16838

It should be:

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

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

You should specify namespace for each element you are mentioning in 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);

Upvotes: 1

Related Questions