2015-11-19 59 views
0

我有兩個用於轉換的輸入。使用XSLT 1.0合併源xml和變量的值

一個是源XML source.xml和看起來像這樣:

<ROOT> 
    <row> 
     <id>1</id> 
     <value>FooBar</value> 
    </row> 
    <row> 
     <id>2</id> 
     <value>Bar</value> 
    </row> 
    <row> 
     <id>3</id> 
     <value>FooFoo</value> 
    </row> 
</ROOT> 

另一種是通過參數(<xsl:param name="input" />)轉換成變換供給。結構與上面的XML相同。但包含不同數量的行和不同的值。

<ROOT> 
    <row> 
     <id>1</id> 
     <value>Foo</value> 
    </row> 
    <row> 
     <id>2</id> 
     <value>Bar</value> 
    </row> 
</ROOT> 

現在我需要合併這些輸入。我想遍歷source.xml,併爲每一行的id決定是否有相同的id在變量和更新。如果變量$input中不存在相同的ID,我想創建新的行。 換句話說:source.xml代表新數據,而輸入參數代表已有的數據。我希望他們合併。我想你明白了。

我嘗試了很多方法來解決這個問題,但我總是在比較創建不必要的行時比較id。這些限制是:

  • XSLT 1.0限制。
  • 用於比較的輸入只能通過使用XSLT參數導入。

輸出應該是這樣的:

<ROOT> 
    <row> 
     <id>1</id> 
     <value>FooBar</value> 
    </row> 
    <row> 
     <id>2</id> 
     <value>Bar</value> 
    </row> 
    <row> 
     <id>3</id> 
     <value>FooFoo</value> 
    </row> 
</ROOT> 
+0

好你的參數有什麼類型?一個節點集,一個結果樹片段,一個帶有XML標記的字符串?只顯示''不會告訴我們你的參數的類型。 –

+0

嗯,這很難說,因爲參數是從引擎自動提供的,我無法控制它。我認爲這是節點集或帶有XML標記的字符串。我知道我可以通過它調用模板並運行XPath表達式。我希望它有幫助 – Allwe

+0

如果你可以使用XPath,那麼它是一個節點集。爲何輸​​出具有' 更新 '和'不 '如果'source.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="input" /> 

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

<xsl:template match="/ROOT"> 
    <xsl:copy> 
     <xsl:apply-templates/> 
     <xsl:apply-templates select="$input/ROOT/row[not(id = current()/row/id)]"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 
+0

這樣做的技巧,謝謝:) – Allwe