我是 XSLT 的新手,我正在處理一個棘手的 xml 轉換要求。我的源 xml 如下所述。
<Level_0>
<Level_1>
<Level_2>
<Level_3>hello</Level_3>
<Level_4>
<Header>
<Value>SomeValue</Value>
</Header>
<SalesInvoice>
<Item>
<Detail>
<Position>1</Position>
</Detail>
</Item>
</SalesInvoice>
<SalesInvoice>
<Item>
<Detail>
<Position>2</Position>
</Detail>
</Item>
</SalesInvoice>
<SalesInvoice>
<Item>
<Detail>
<Position>3</Position>
</Detail>
</Item>
</SalesInvoice>
</Level_4>
</Level_2>
</Level_1>
</Level_0>
要求 - 我需要讓每個專案的父級達到 level_1,這意味著輸出應該如下所述。基本上,應該為 level_1 中的每個專案重復所有內容。
<Level_0>
<Level_1>
<Level_2>
<Level_3>hello</Level_3>
<Level_4>
<Header>
<Value>SomeValue</Value>
</Header>
<SalesInvoice>
<Item>
<Detail>
<Position>1</Position>
</Detail>
</Item>
</SalesInvoice>
</Level_4>
</Level_2>
</Level_1>
<Level_1>
<Level_2>
<Level_3>hello</Level_3>
<Level_4>
<Header>
<Value>SomeValue</Value>
</Header>
<SalesInvoice>
<Item>
<Detail>
<Position>2</Position>
</Detail>
</Item>
</SalesInvoice>
</Level_4>
</Level_2>
</Level_1>
<Level_1>
<Level_2>
<Level_3>hello</Level_3>
<Level_4>
<Header>
<Value>SomeValue</Value>
</Header>
<SalesInvoice>
<Item>
<Detail>
<Position>3</Position>
</Detail>
</Item>
</SalesInvoice>
</Level_4>
</Level_2>
</Level_1>
</Level_0>
XSLT 我試過了。但我得到了奇怪的輸出。
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" indent="yes"/>
<xsl:template match="SalesInvoice">
<NewInvoice>
<xsl:copy-of select="../../../../Level_1/descendant::*[not(name()='SalesInvoice' or ancestor::SalesInvoice)]"/>
<xsl:copy-of select="."/>
</NewInvoice>
</xsl:template>
</xsl:stylesheet>
uj5u.com熱心網友回復:
這是處理它的一種方法。對于每個SalesInvoice程序,應用模板從它開始,但作為引數Level_1傳遞(我使用了@tunnel,但您可以顯式定義引數并在每個模板的每個級別傳遞它)。在模板匹配中,如果是 ,則僅復制內容,否則將被洗掉。SalesInvoiceSalesInvoice$invoice-context
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Level_0">
<xsl:copy>
<xsl:for-each select="//SalesInvoice">
<xsl:apply-templates select="ancestor::Level_1" mode="repeat">
<xsl:with-param name="invoice-context" select="." tunnel="yes"/>
</xsl:apply-templates>
</xsl:for-each>
</xsl:copy>
</xsl:template>
<xsl:template match="*" mode="repeat">
<xsl:copy>
<xsl:apply-templates select="@*|node()" mode="repeat"/>
</xsl:copy>
</xsl:template>
<xsl:template match="SalesInvoice" mode="repeat">
<xsl:param name="invoice-context" tunnel="yes"/>
<xsl:if test="generate-id(.) eq generate-id($invoice-context)">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/434196.html
