【问题标题】:Select element value with xpath使用 xpath 选择元素值
【发布时间】:2014-01-05 21:04:35
【问题描述】:

给定这个 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);

【问题讨论】:

    标签: c# .net xml xpath


    【解决方案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);
    

    【讨论】:

    • 像魅力一样工作,是否有指向解释此内容的文档的链接?
    【解决方案2】:

    应该是:

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

    【讨论】:

    • 正确,Sergey Berezovskiy 稍微快一点,所以我接受了那个
    • 没问题。他的也不那么冗长。
    猜你喜欢
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2021-02-23
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    相关资源
    最近更新 更多