2017-03-07 125 views
0

我有多个xml文件需要处理并写入单个xml文件。我已经完成了大部分转换,并且在一个xml文件中找到特定元素的地方。使用xslt查找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> 

它不工作,因为我在函数声明中犯了一些错误。你能帮忙吗?

回答

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> 
+0

正在调用key中的文档引用吗?当我试图调用它时,它不显示任何结果。钥匙('part-ref','head shaft',$ partdoc)/ code –

+0

@SrikrishnaPothukuchi,我用一个完整的例子编辑了答案,这个例子对我来说工作得很好。如果仍存在问题,请编辑显示最少但完整的XML示例,您现在拥有的XSLT,输出的结果以及有关使用过的XSLT处理器的信息。 –

+0

非常感谢马丁。正如您正确地指出的那样,这是我的Eclipse的问题。我使用Eclipse Neon使用Saxon 9.7。有时它的行为不正确。当我使用XML Spear时,相同的代码以100%的精度工作。 –