css - 使用 CSS 或 XPath 排除另一个元素中包含的元素

标签 css ruby xml xpath css-selectors

这是一段 XML:

<xml>
  <section>
    <element>good</element>
    <section class="ignored">
      <element>bad</element>
    </section>
  </section>
</xml>

选择所有元素section.ignored内的所有元素非常简单:

@doc.css('element').text
 => "goodbad" 
@doc.css('section.ignored element').text
 => "bad" 

但是如何选择 section.ignored的所有元素?这不起作用:

@doc.css('section:not(.ignored) element').text
 => "goodbad" 

...因为这实际上意味着“不被忽略的任何部分中包含的所有元素”,包括包装其他所有内容的顶级部分!

额外的变化:与上面的简化示例不同,我必须处理的真实 XML 嵌套到任意深度,包括被忽略的部分内的部分。

是的,我可以从 Ruby 中的完整数组中减去坏数组,然后就到此为止,但如果可能的话,我更喜欢纯 CSS 解决方案(或者,如果必须的话,XPath)。

最佳答案

how do I select all elements that are not inside section.ignored ?

使用此 XPath 表达式:

//element[not(ancestor::section[@class='ignored'])]

这将选择任何名为 element 的元素,该元素没有名为 section 的祖先,其 class 属性的字符串值是该字符串“忽略” .

基于 XSLT 的验证:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
     <xsl:copy-of select=
     "//element[not(ancestor::section[@class='ignored'])]"/>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:

<xml>
    <section>
        <element>good</element>
        <section class="ignored">
            <element>bad</element>
        </section>
    </section>
</xml>

对上述 XPath 表达式进行求值,并将所有(在本例中仅为一个)选定的节点复制到输出。产生了想要的正确结果:

<element>good</element>

关于css - 使用 CSS 或 XPath 排除另一个元素中包含的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10240040/

相关文章:

php - Curl 没有获得带有 https url 的 xml 响应?

css - 包含样式表时导致错误的 XSL 文件

javascript - 如何将某些样式应用于打印页面上的第一个和最后一个元素?

Firefox CSS3 转换不工作

ruby-on-rails - Ruby on Rails 中的竞争条件

ruby-on-rails - ROR 相当于 Phoenix Mix?

html - 使div不受其他div大小的影响

html - 使用 RoyalSlider 全屏时如何显示标题

ruby-on-rails - 安装了 Gem 但 'command not found'

xml - Scala 的 XOM 模拟?