xml - 通过指定另一个值来拉取一个值

标签 xml xpath

对于以下 XML 片段 -

<response uri="http://campaigns.zoho.com/api/recentsentcampaigns" version="1">
  <status>success</status>
  <code>0</code>
  <recent-sent-campaigns>
        <campaign no="1">
              <fl val="campaign_key">somekeyvalue</fl>
              <fl val="sent_date_string">08 Jun 2015, 11:55 PM</fl>
              <fl val="sent_time">1433850936000</fl>
              <fl val="campaign_name">Test for Mailing List</fl>
              <fl val="created_date_string">08 Jun 2015, 10:38 PM</fl>
              <fl val="campaigntype">normal</fl><fl val="created_time">1433846306000</fl>
        </campaign>
  </recent-sent-campaigns>

我想通过指定campaign_name 文本来获取campaign_key 文本。我知道如何通过指定事件编号(在本例中为“1”)来返回campaign_key 文本,但我需要能够将campaign_name 作为参数传递(在本例中为“Test for Mailing List”)并返回键(在这种情况下,“somekeyvalue”)。

最佳答案

要根据名称检索事件 key ,请使用

/response/recent-sent-campaigns/campaign[fl[@val = 'campaign_name'] = 'Test for Mailing List']/fl[@val = 'campaign_key']

意思是
/response                   select the `response` element
/recent-sent-campaigns      select its children `recent-sent-campaigns`
/campaign                   select its children `campagin`
[fl[@val = 'campaign_name'] but only if there is a child element called `fl` which has an
                            attribute called `val` whose value is "campaign_name"
= 'Test for Mailing List']  and only if the text content of that `fl` element is "Test for
                            Mailing List"
/fl[@val = 'campaign_key']  of any elements satisfying this condition, select their
                            children `fl` where there is an attribute `val` whose value is
                            equal to "campaign_key"

并产生结果:
<fl val="campaign_key">somekeyvalue</fl>

如果您只想返回此元素的文本内容,请附加 /text()在末尾:
/response/recent-sent-campaigns/campaign[fl[@val = 'campaign_name'] = 'Test for Mailing List']/fl[@val = 'campaign_key']/text()

结果将是
somekeyvalue

关于xml - 通过指定另一个值来拉取一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30766627/

相关文章:

xml - 创建新节点<xi:include>

java - 如何在使用 ItemWriter 步骤时限制 Spring Batch 的大小?

xpath - 如何从 XML 获取 XPath?

Python TLS 握手 XMPP

android - 在 fragment 中获取 Assets

java - 有没有办法结合 xpath 和 regexp 来提取节点值的一部分?

xml - 如果 XPATH 中不存在节点,如何返回常量?

xml - xpath 日期比较

xml - 使用 Xpath 进行 XSLT 处理的说明

android - 如何在构建时设置 strings.xml 值?