我需要使用 xslt 將專案標簽轉換為它們各自的父節點。
我有這個輸入。
<root>
<field>111</field>
<list1>
<item>
<field1>aa</field1>
<field2>valuea</field2>
</item>
<item>
<field1>bb</field1>
<field2>valueb</field2>
</item>
</list1>
<list2>
<item>
<field3>cc</field3>
<field4>valuec</field4>
</item>
<item>
<field3>dd</field3>
<field4>valued</field4>
</item>
</list2>
我正在使用這個 xsl 但不作業。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="list1/item">
<list1>
<xsl:apply-templates select="@*|node()"/>
</list1>
</xsl:template>
<xsl:template match="list2/item">
<list2>
<xsl:apply-templates select="@*|node()"/>
</list2>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="list1/*">
<xsl:apply-templates select="node()"/>
</xsl:template>
<xsl:template match="list2/*">
<xsl:apply-templates select="node()"/>
</xsl:template>
</xsl:樣式表>
預期的輸出是這樣的。
<root>
<field>111</field>
<list1>
<field1>aa</field1>
<field2>valuea</field2>
</list1>
<list1>
<field1>bb</field1>
<field2>valueb</field2>
</list1>
<list2>
<field3>cc</field3>
<field4>valuec</field4>
</list2>
<list2>
<field3>dd</field3>
<field4>valued</field4>
</list2>
我嘗試使用上面的代碼,但它回傳的 xml 根本沒有父標簽。怎么可能做到這一點?
uj5u.com熱心網友回復:
怎么樣:
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="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="list1 | list2">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="item">
<xsl:element name="{name(..)}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
添加:
如果其中沒有專案,它將洗掉標簽 list2。我怎么能把它留在那里?
改變:
<xsl:template match="list1 | list2">
到:
<xsl:template match="list1[item] | list2[item]">
在 XSLT 2.0 中,您可以:
<xsl:template match="(list1 | list2)[item]">
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/415616.html
標籤:
上一篇:Xml沒有縮進字符但有新行
