这是一段 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/