2016-07-28 44 views
0

我們使用的一種產品能夠將配置信息輸出爲XML,但在該輸出文件中不是包含實際的主機標識符(名稱),而是爲每個標識符使用一種GUID引用。XSLT用於查找一個XML中的值並替換爲另一個XML文件

我做了一個XML文件,其中包含主機標識符GUID和實際主機標識符(查找)之間的「映射」,並且我想實現一個XSLT,它將通過配置文件並替換所有主機標識符GUID與主機標識符名稱,它將從我製作的其他XML文件(lookup.xml)中查找。

這裏的lookup.xml文件的樣子:

<?xml version="1.0"?> 
<hostids> 

    <hostid name="e687903c-d185-4560-9117-c60f386b76c1">Agent</hostid> 
    <hostid name="b9230962-13ca-4d23-abf8-d3cd1ca4dffc">test2</hostid> 

</hostids> 

,這裏是什麼配置文件的樣子(我跑了通過一些處理原始文件可以解決):

<?xml version="1.0"?> 
<resources> 

    <resource><host>e687903c-d185-4560-9117-c60f386b76c1</host><url>/console/**</url></resource> 
    <resource><host>b9230962-13ca-4d23-abf8-d3cd1ca4dffc</host><url>/ServiceByName</url></resource> 

</resources> 

這裏是輸出應該是什麼樣子:

<?xml version="1.0"?> 
<resources> 

    <resource><host>Agent</host><url>/console/**</url></resource> 
    <resource><host>test2</host><url>/ServiceByName</url></resource> 

</resources> 

我與xsltpro工作c在RedHat機器上,我認爲是XSLT 1.0。

我試圖得到這個工作與我在這裏找到幾個不同的例子XSLT文件,例如:

XSLT "replace" values with another file matching by attribute

,但一直沒能得到其中的任何工作。

任何人都可以提供一個XSLT 1.0的例子,可以實現這個目標嗎?

P.S.這是另一個有示例的線程,XSLT 1.0示例不適用於我。當我運行它(修改後匹配我的元素名稱等)後,它看起來像只是包裝了整個原始XML。

How to use attribute values from another XML file as an element value selection in the current XML

回答

1

試試這個方法吧?

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:param name="path-to-lookup" select="'lookup.xml'" /> 

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

<xsl:template match="host"> 
    <xsl:copy> 
     <xsl:value-of select="document($path-to-lookup)/hostids/hostid[@name = current()]" /> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

或者,如果你喜歡:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:param name="path-to-lookup" select="'lookup.xml'" /> 

<xsl:key name="host" match="hostid" use="@name" /> 

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

<xsl:template match="host"> 
    <xsl:copy> 
     <xsl:variable name="host-id" select="." /> 
     <!-- switch context to lookup document in order to use key --> 
     <xsl:for-each select="document($path-to-lookup)"> 
      <xsl:value-of select="key('host', $host-id)" /> 
     </xsl:for-each> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 
+0

michael.hor257k - 我想你的第一個XSLT和它的工作完美!! – user555303

相關問題