2017-03-07 117 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%的精度工作。 –