选择xml元素匹配属性

时间:2015-11-04 21:06:01

标签: xml xslt xpath

我有以下xml内容:

<root>
    <content>
        <figure id="fig-001">
            <graphic id="fig-001-graId-001"/>
            <graphic id="fig-001-graId-002"/>
            <graphic id="fig-001-graId-003"/>
        </figure>
        <figure id="fig-002">
            <graphic id="fig-002-graId-001"/>
            <graphic id="fig-002-graId-002"/>
        </figure>        
        <refs>
            <ref ref-id="fig-001-graId-001" type="test"/>
            <ref ref-id="fig-002-graId-001" type="test"/>
        </refs>
    </content>
</root>

我使用oXygen

我点击了一个元素refs / ref,例如在

<ref ref-id="fig-01-graId-001 type="test" />

我想要一个x计数&#39; graphic&#39;图中的元素有图形/ @ id = ref / @ ref-id(我点击的时候),类似的东西:

count(// content / figure / graphic [@id = // ref / @ ref-id] / parent :: / graphic)==&gt; 3(带有ref-id = fig-001-graId-001的图形的父级有3个图形元素)

3 个答案:

答案 0 :(得分:1)

您特别提到了oXygen,所以这里有一个选项:

for $refid in @ref-id return count(//figure[graphic/@id = $refid]/graphic)

需要在XPath工具栏中使用此XPath 2.0(确保选择了XPath 2.0)。我认为您不能使用XPath构建器,因为您丢失了上下文。

我唯一一次能让它正常工作100%的时间是确保当我点击ref元素时,元素的开头和结尾下面的2个括号(点击后)在XPath工具栏中运行XPath)。这可确保上下文正确无误。 (这可以通过<ref之后直接点击来完成。)

括号在下面的屏幕截图中突出显示。另请注意屏幕截图底部的正确结果:

enter image description here

更新:添加ancestor-or-self::*[1]似乎有助于获取正确的上下文,无论您点击的元素位于何处:

for $refid in ancestor-or-self::*[1]/@ref-id return count(//figure[graphic/@id = $refid]/graphic)

答案 1 :(得分:0)

我想你想做:

count(//graphic[@id=//ref/@ref-id]/../graphic)

或者,如果您愿意:

count(//figure[graphic/@id=//ref/@ref-id]/graphic)

答案 2 :(得分:0)

使用密钥可以使用

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:key name="id" match="figure" use="graphic/@id"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/">
        <xsl:value-of select="count(key('id', //ref/@ref-id)/graphic)"/>
    </xsl:template>
</xsl:transform>

请参阅http://xsltransform.net/ej9EGc1

相关问题