![](/img/trans.png)
[英]xslt to add existing node in xml to another node based on a particular value using for each loop
[英]When XSLT for-each is in a loop. How can I add an attribute or node to that XML based on other XML value. USING XSLT
誰能幫我解決這個問題?
我有一個XML,並根據某些條件過濾值。 將過濾后的xml存儲在變量中。 在過濾條件時,我正在嘗試向過濾的xml中添加屬性或節點,但它對我不起作用。
輸入XML:
<root>
<a id="13">
<b>XXX1</b>
<c>YYY1</c>
</a>
<a id="2">
<b>XXX2</b>
<c>YYY2</c>
</a>
<a id="15">
<b>XXX3</b>
<c>YYY3</c>
</a>
<a id="37">
<b>XXX4</b>
<c>YYY4</c>
</a>
<a id="51">
<b>XXX5</b>
<c>YYY5</c>
</a>
</root>
另一種XML存儲在稱為“數據”的變量中(用於過濾):
<sample>
<con id="37" order="1"/>
<con id="13" order="2"/>
<con id="51" order="3"/>
<con id="2" order="4"/>
<con id="15" order="5"/>
</sample>
使用XSLT,我試圖以這種方式過濾和添加元素。
<xsl:variable name="filteredData">
<newroot>
<xsl:for-each select="/root/a[@id > 14]">
<xsl:if test="msxsl:node-set($data)/sample/con[@id = current()/@id]/@id = current()/@id">
<xsl:element name="order">
<xsl:value-of select="msxsl:node-set($data)/sample/con[@id = current()/@id]/@order"/>
</xsl:element>
</xsl:if>
</xsl:for-each>
</newroot>
</xsl:variable>
輸出XML(即“ filteredData”變量應包含以下XML):
<newroot>
<a id="15">
<b>XXX3</b>
<c>YYY3</c>
<order>5</order>
</a>
<a id="37">
<b>XXX4</b>
<c>YYY4</c>
<order>1</order>
</a>
<a id="51">
<b>XXX5</b>
<c>YYY5</c>
<order>3</order>
</a>
</newroot>
嘗試使用具有此示例中的鍵功能的查找表提示:XSLT查找表
我能夠獲得以下代碼片段,以生成與您上面的輸出匹配的xml文檔。 下面的xslt中的過濾數據是從單獨的文檔中加載的,但是應該很容易適應。
<xsl:key name="id-lookup" match="con" use="@id"/>
<xsl:variable name="id-top" select="document('<lookup file>')/sample"/>
<xsl:template match="root">
<newroot>
<xsl:for-each select="a[@id > 14]">
<xsl:copy>
<xsl:copy-of select="@*|node()"/>
<xsl:element name="order">
<xsl:apply-templates select="$id-top">
<xsl:with-param name="curr-label" select="."/>
</xsl:apply-templates>
</xsl:element>
</xsl:copy>
</xsl:for-each>
</newroot>
</xsl:template>
<xsl:template match="sample">
<xsl:param name="curr-label"/>
<xsl:value-of select="key('id-lookup', $curr-label/@id)/@order"/>
</xsl:template>
基於輸入,現在我嘗試並實現了另一種表示形式。
新的XSLT代碼:
<xsl:variable name="filteredData">
<newroot>
<xsl:for-each select="/root/a[@id > 14]">
<xsl:copy>
<xsl:copy-of select="@*|node()"/>
<xsl:element name="Order">
<xsl:choose>
<xsl:when test="msxsl:node-set($data)/sample/con[@id = current()/@id]/@id = current()/@id">
<xsl:value-of select="msxsl:node-set($data)/sample/con[@id = current()/@id]/@order"/>
</xsl:when>
<xsl:otherwise>
<xsl:text> </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:element>
</xsl:copy>
</xsl:for-each>
</newroot>
</xsl:variable>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.