【问题标题】:XPath get element by text of previous elementXPath 通过前一个元素的文本获取元素
【发布时间】:2016-07-01 05:00:24
【问题描述】:

我需要根据前一个元素文本获取第二个元素的文本 (Description)。

<world>
  <continent>europe</continent>
  <description>germany, france, italy, spain</description>
</world>
<world>
  <continent>asia</continent>
  <description>japan, thailand, china</description>
</world>
<world>
  <continent>africa</continent>
  <description>south africa, simbabwe, tansania</description>
</world>

XPath:

//world[continent="africa"]/description

我尝试了几种变体,但没有一种效果很好。 有什么想法吗?

【问题讨论】:

  • 什么价格要素?它在 XML 中的什么位置?
  • 抱歉。在写作时改变故事。
  • 您的 xml 没有根元素,它无效。添加后,/world 将一无所获。您需要再添加一个斜线才能使其正常工作//world[continent="africa"]/description。

标签: xml xpath


【解决方案1】:

这个 XPath,

//world[continent="africa"]/description/text()

通过添加包装器根元素应用于您的 XML 格式,

<r> 
  <world> 
    <continent>europe</continent>  
    <description>germany, france, italy, spain</description> 
  </world>  
  <world> 
    <continent>asia</continent>  
    <description>japan, thailand, china</description> 
  </world>  
  <world> 
    <continent>africa</continent>  
    <description>south africa, simbabwe, tansania</description> 
  </world> 
</r>

将产生

south africa, simbabwe, tansania

根据要求。

【讨论】:

    【解决方案2】:

    我觉得应该是

    //world/continent[text()="africa"]/following-sibling::description/text()
    

    意思是:通过文本内容等于“africa”获取continent节点,从那里取出下一个兄弟节点,应该是描述。

    【讨论】:

    • 我认为@MCG 要求的是//world/continent[text()="africa"]/following-sibling::description[1]/text(),即不选择所有后续兄弟姐妹,而只选择第一个。
    • 我认为在这种情况下这并不重要。
    • 它确实有效,但它比必要的复杂一点:following-sibling:: 是 not necessary。
    • @kjhughes 我同意它可以更简单,没想到你发布的更简单的版本。
    猜你喜欢
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 2020-08-14
    • 2015-09-02
    • 2020-07-19
    • 2015-04-02
    • 2013-10-14
    • 2023-03-25
    相关资源
    最近更新 更多