如何计算具有相同属性值的元素 [英] How to count elements with same attribute value

查看:32
本文介绍了如何计算具有相同属性值的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信这是一个简单的方法,但我只是不为树只见树木.

I'm sure this is an easy one but i'm just not to see the wood for the trees.

我有一个如下所示的 XML:

I'm having an XML that look like this:

   <root>
    <profil>
        <e1 a="2">1</e1>
        <m1 a="3">1</m1>
        <e2 a="4">1</e2>
        <m2 a="5">1</m2>
    </profil>
    <profil>
        <e1 a="5">1</e1>
        <m1 a="3">1</m1>
        <e2 a="4">1</e2>
        <m2 a="4">1</m2>
    </profil>
    <profil>
        <e1 a="7">1</e1>
        <m1 a="7">1</m1>
        <e2 a="4">1</e2>
        <m2 a="2">1</m2>
    </profil>
</root>

现在我想知道每个/profil 有多少/m*/@a 等于 e*/@a.所以我想出了以下 XSLT:

Now I want to know how many /m*/@a are equal to e*/@a per /profil. So I came up with the following XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="*">
        <xsl:element name="root">
            <xsl:for-each select="/root/profil">
                <xsl:element name="count">
                    <xsl:value-of select="count(*[contains(name(), 'm') and ./@a = //*[contains(name(),'e')]/@a])"/>
                </xsl:element>
            </xsl:for-each>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

但结果是错误的:

<root>
    <count>1</count>
    <count>1</count>
    <count>2</count>
</root>

应该是

<root>
    <count>0</count>
    <count>1</count>
    <count>1</count>
</root>

有人建议我做错什么吗?

Does anyone has a suggestion what I'm doing wrong?

推荐答案

将 XPath 替换为正确的 XPath,即:

Replace the XPath with the correct one, which is:

<xsl:value-of select="count(*[substring(name(),1,1)='m' 
      and ./@a = ../*[substring(name(),1,1)='e']/@a])"/>

我使用 substring 来匹配第一个属性字符,而不是 contains 匹配字符串中的任何字符.

I've used substring to match the first attribute character in place of contains which matches any character in a string.

这篇关于如何计算具有相同属性值的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆