我目前正在執行一項任務,在該任務中我需要遍歷 XML 檔案的兩個不同部分(兩個檔案之前已合并到這個部分)并搜索 ID。
如果 ID、顏色和數量值在檔案的兩個位置都匹配,我需要選擇第二個檔案 (fileB) 中的所有欄位。
如果沒有,那么我需要從第一個檔案 (fileA) 中選擇欄位。
這是 XML 的示例:
<root>
<fileA>
<data>
<id>123</id>
<color>Green</color>
<quantaties>5</quantaties>
</data>
<data>
<id>456</id>
<color>Red</color>
<quantaties>7</quantaties>
</data>
<data>
<id>789</id>
<color>Blue</color>
<quantaties>9</quantaties>
</data>
</fileA>
<fileB>
<data>
<id>456</id>
<color>Red</color>
<quantaties>7</quantaties>
<date>15-07-2021</date>
<reason>Internal</reason>
</data>
</fileB>
</root>
在上面的示例中,兩個檔案中僅存在 id 456,顏色為紅色,數量為 7。在這種情況下,我想從 fileB 填充那個。所以我想要的輸出是:
<root>
<newFile>
<data>
<id>123</id>
<color>Green</color>
<quantaties>5</quantaties>
</data>
<data>
<id>456</id>
<color>Red</color>
<quantaties>7</quantaties>
<date>15-07-2021</date>
<reason>Internal</reason>
</data>
<data>
<id>789</id>
<color>Blue</color>
<quantaties>9</quantaties>
</data>
</newFile>
</root>
請記住,多個欄位必須匹配,因此不僅僅是 ID。還有顏色和數量,以便選擇 fileB 資料。誰能幫我解決這個問題?掙扎了一段時間。
uj5u.com熱心網友回復:
我會這樣做:
XSLT 3.0
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:key name="fileB" match="fileB/data" use="id||color||quantaties"/>
<xsl:template match="/root">
<xsl:copy>
<newFile>
<xsl:for-each select="fileA/data">
<xsl:copy>
<xsl:copy-of select="*, key('fileB', id||color||quantaties)/(* except (id|color|quantaties))"/>
</xsl:copy>
</xsl:for-each>
</newFile>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
請注意,這假定color不以數字開頭或結尾 - 否則您應該在key值中插入分隔符。
或者你可以這樣做:
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<xsl:copy>
<newFile>
<xsl:for-each-group select="*/data" group-by="id, color, quantaties" composite="yes">
<xsl:copy>
<xsl:for-each-group select="current-group()/*" group-by="name()" >
<xsl:copy-of select="."/>
</xsl:for-each-group>
</xsl:copy>
</xsl:for-each-group>
</newFile>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368123.html
