我有一個包含數百條這種格式記錄的 XML(此處僅顯示 2 條)
<assessment>
<subject>
<Name>470 470 015</Name>
<LAD>3.446887644423149</LAD>
<LAD>3.446887644423149</LAD>
<LM>4.049357373198344</LM>
<LM>4.049357373198344</LM>
<RCA>3.283339910532276</RCA>
<RCA>3.283339910532276</RCA>
</subject>
<subject>
<Name>230 230067</Name>
<LAD>2.392278459908628</LAD>
<LAD>2.392278459908628</LAD>
<LM>3.50258194988953</LM>
<LM>3.50258194988953</LM>
<RCA>3.274917502338067</RCA>
<RCA>3.274917502338067</RCA>
</subject>
</assessment>
我想洗掉重復的節點,使其看起來像這樣
<assessment>
<subject>
<Name>470 470 015</Name>
<LAD>3.446887644423149</LAD>
<LM>4.049357373198344</LM>
<RCA>3.283339910532276</RCA>
</subject>
<subject>
<Name>230 230067</Name>
<LAD>2.392278459908628</LAD>
<LM>3.50258194988953</LM>
<RCA>3.274917502338067</RCA>
</subject>
</assessment>
根據之前對類似問題(https://stackoverflow.com/a/37078109/18941723)的回答中記錄的代碼,我能夠處理第一條記錄,但不能處理檔案中的所有記錄。
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:for-each-group select="*" group-by="name()">
<xsl:apply-templates select="current-group()[1]"/>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
uj5u.com熱心網友回復:
嘗試改變:
match="/*"
到:
match="subject"
馬丁評論道:
當前答案和您的嘗試身份根據元素/節點名稱重復。我想知道您是否可以在一個元素中包含多個具有相同名稱的元素(例如
LAD),這些subject元素可以具有不同的值,以及在這種情況下您需要做什么。
composite="yes"一種選擇是通過指定并添加.ornormalize-space()來使用復合鍵group-by。這將保留每個元素名稱/值組合的一個實體。
例子...
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" expand-text="yes">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="subject">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:for-each-group select="*" group-by="name(),normalize-space()" composite="yes">
<xsl:apply-templates select="current-group()[1]"/>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
uj5u.com熱心網友回復:
你有正確的方法,我會這樣做:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="subject">
<xsl:copy>
<xsl:for-each-group select="*" group-by="name()">
<xsl:copy-of select="current-group()[1]"/>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
看到它在這里作業:https ://xsltfiddle.liberty-development.net/6qjt5SC
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/463993.html
