gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:07:34 24 4
gpt4 key购买 nike

这是一段 XML:

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

选择所有 elementssection.ignored 内的所有 elements 非常容易:

@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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com