通过XSLT将xml文档的名称添加到元素ID

时间:2018-04-05 17:11:17

标签: xml xslt document

我有一个名为“document-a-f-52.xml”的xml文档,其中包含以下内容。

INPUT:

<?xml version="1.0" encoding="UTF-8"?>
<ws>
    <w id="w_1">how</w>
    <w id="w_2">to</w>
    <w id="w_3">add</w>
    <w id="w_4">document</w>
    <w id="w_5">number</w>
    <w id="w_6">to</w>
    <w id="w_7">this</w>
    <w id="w_8">.</w>
</ws>

我想将文档名称'52'的数字部分(假设文档的名称是document-a-f-52.xml)添加到“w”元素的id中,如下所示:

 <?xml version="1.0" encoding="UTF-8"?>
 <ws>
    <w id="w_1_52">how</w>
    <w id="w_2_52">to</w>
    <w id="w_3_52">add</w>
    <w id="w_4_52">document</w>
    <w id="w_5_52">number</w>
    <w id="w_6_52">to</w>
    <w id="w_7_52">this</w>
    <w id="w_8_52">.</w>
</ws>

我想知道如何从文档名称中获取数字部分(最后两位数字)并将其添加到“w”元素ID中。

2 个答案:

答案 0 :(得分:0)

根据您使用的XSLT处理器,您可以通过参数将numeric传递给XSLT样式表。

您的XSLT可能如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
    <xsl:param name="numeric" select="52" />

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

    <!-- This template adds the 'numeric' value to the attribute 'id' -->
    <xsl:template match="@id">
        <xsl:attribute name="id">
            <xsl:value-of select="concat(.,'_',$numeric)" />
        </xsl:attribute>
    </xsl:template>  
</xsl:stylesheet>

您的XSLT处理器可以将numeric参数传递给模板 例如,使用xsltproc,您可以使用

xsltproc --stringparam numeric 100 a.xslt a.xml

获得像

这样的结果
<ws>
    <w id="w_1_100">how</w>
    <w id="w_2_100">to</w>
    <w id="w_3_100">add</w>
    <w id="w_4_100">document</w>
    <w id="w_5_100">number</w>
    <w id="w_6_100">to</w>
    <w id="w_7_100">this</w>
    <w id="w_8_100">.</w>
</ws>

其他XSLT处理器可以处理以不同方式传递的参数。

答案 1 :(得分:0)

使用XSLT 3或2,您可以访问document-uri()tokenize以查找文件名作为最后一个标记,并用空字符串替换任何非数字,所以使用XSLT 3需要是

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:param name="suffix" as="xs:string" select="'_' || replace(tokenize(document-uri(), '/')[last()], '[^0-9]', '')"/>

    <xsl:template match="w/@id">
        <xsl:attribute name="{name()}" select=". || $suffix"/>
    </xsl:template>

</xsl:stylesheet>

使用XSLT 2,您需要将上面使用的xsl:mode on-no-match="shallow-copy"拼写为身份转换模板,并使用concat函数代替|| concat运算符。