XSLT 1.0: using EXSLT to get element name according to substring

跟風遠走 提交于 2020-01-07 08:33:15

问题


I have the following XML and I want to get only the element names that start with "MBH":

<?xml version="1.0" encoding="UTF-8"?>
<GenericRecs>
<GenericRecord>
    <record>
        <MBH1/>
    </record>
    <record>
        <BAL1/>
    </record>
    <record>
        <MBH2/>
    </record>
    <record>
        <BAL2/>
    </record>
    <record>
        <PAY2/>
    </record>
    <record>
        <MBH3/>
    </record>
    <record>
        <BAL3/>
    </record>
    <record>
        <PAY3/>
    </record>
</GenericRecord>
</GenericRecs>

I have the following XSLT:

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

<xsl:variable name="x" select="ext:node-set(substring(local-name(//record/child::*),1,3)='MBH')"/>

<xsl:variable name="mbh">
    <xsl:for-each select="$x">
            <item>
                <xsl:copy>
                    <xsl:value-of select="local-name(.)"/>
                </xsl:copy> 
            </item>
    </xsl:for-each>
</xsl:variable>

<xsl:template match="/">
    <xsl:apply-templates select="$mbh"/>
</xsl:template>
</xsl:stylesheet>

But all I get is an error "Description: Can not convert #RTREEFRAG to a NodeList!" I am using EXSLT but I do not understand why I would get that error.

Thank you for your help, Peter


回答1:


I have the following XML and I want to get only the element names that start with "MBH":

What's wrong with

<xsl:apply-templates select="//record/*[starts-with(name(), 'MBH')]" />

?

A few notes:

  • Use name() rather than local-name() whenever possible. There are no namespaces in your input so there is no difference between them anyway.
  • the child:: axis is the default. child::* is equivalent to *.
  • If you can do anything about it, change the input. Having <xyz1> through <xyz3> is not very clever, unless <xyz3> actually is completely different from <xyz1> (instead of merely being "the third <xyz>").
    In that case <xyz num="1"> would be sensible. If they are completely different, they should not have a similar name.


来源:https://stackoverflow.com/questions/12313393/xslt-1-0-using-exslt-to-get-element-name-according-to-substring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!