使用xslt

时间:2017-03-07 10:47:06

标签: xml xslt xpath

我有多个要处理的xml文件并写入一个xml文件。我完成了大部分的转换,并在一个xml文件中找到特定元素的地方进行了攻击。

源xml之一是(parts.xml):

<parts>
    <part>
        <name>head shaft</name>
        <code>100</code>
    </part>
    ...
</parts>

另一个来源xml(price.xml):

<price-list>
    <price>
        <part-name>head shaft</part-name>
        <cost>28.45</cost>
        ...
    </price>
    ...
</price-list>

我必须只获取属于特定名称元素的代码元素。 这只是一个源xml文件,像这样我有很多要处理的文件。

我的输出xml必须像这样(result.xml):

<part-order>
    <part code=100 name="head shaft" price=32.05 qty=1 />
    ...
</part-order>

我获取零件代码的xslt函数是:

<xsl:function name="p:find">
    <xsl:variable name="partdoc" select="document('parts.xml')"/>
    <xsl:param name="str"/>
    <xsl:apply-templates select="$partdoc/p:/parts/part[contains(p:name,  '$str')]"/>
    <xsl:apply-templates select="$partdoc/p:code" />
</xsl:function> 

最后,我想调用这样的函数:

<xsl:template match="/">
    <xsl:copy>
        <xsl:variable name="code">
            <xsl:value-of select="p:find('head shaft')"/>
        </xsl:variable>
        <part code="{'$code'}" name="{'head shaft'}" price="{$somelogic}"/>                     
    </xsl:copy>
</xsl:template>

由于我在函数声明中犯了一些错误,因此无效。你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

定义键<xsl:key name="part-ref" match="parts/part" use="name"/>然后使用全局参数或变量<xsl:variable name="partdoc" select="document('parts.xml')"/>,然后您可以使用<part code="{key('part-ref', 'head shaft', $partdoc)/code}" .../>

没有必要为交叉引用编写函数,因为密钥提供了该函数。

这是一个完整的示例,主要输入文档是

<?xml version="1.0" encoding="UTF-8"?>
<price-list>
    <price>
        <part-name>head shaft</part-name>
        <cost>28.45</cost>
        ...
    </price>
    ...
</price-list>

另一份文件是

<?xml version="1.0" encoding="UTF-8"?>
<parts>
    <part>
        <name>head shaft</name>
        <code>100</code>
    </part>
    ...
</parts>

给出XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:key name="part-ref" match="parts/part" use="name"/>

    <xsl:variable name="partdoc" select="document('parts.xml')"/>

    <xsl:template match="price-list">
        <part-order>
            <xsl:apply-templates/>
        </part-order>
    </xsl:template>

    <xsl:template match="price">
        <part code="{key('part-ref', part-name, $partdoc)/code}" name="{part-name}" price="{cost}" qty="1" />
    </xsl:template>

</xsl:stylesheet>

输出

<part-order>
    <part code="100" name="head shaft" price="28.45" qty="1"/>
    ...
</part-order>