将XML转换为另一种格式并添加行号
我想转换XML并添加行号 示例XML文件如下所示:将XML转换为另一种格式并添加行号,xml,xslt,Xml,Xslt,我想转换XML并添加行号 示例XML文件如下所示: <Wholesale> <Customer> <Name>abc</Name> </Customer> <Customer> <Name>def</Name> </Customer> <Customer> <Name>hij</Name> </Customer>
<Wholesale>
<Customer>
<Name>abc</Name>
</Customer>
<Customer>
<Name>def</Name>
</Customer>
<Customer>
<Name>hij</Name>
</Customer>
<Product>
<productid>800</productid>
</Product>
<Product>
<productid>900</productid>
</Product>
</Wholesale>
abc
def
你好
800
900
希望此文件采用以下格式:
<Wholesale>
<Customer>
<Name>abc</Name>
<Product>
<rowno>1</rowno>
<productid>800</productid>
</Product>
<Product>
<rowno>2</rowno>
<productid>900</productid>
</Product>
</Customer>
<Customer>
<Name>def</Name>
<Product>
<rowno>1</rowno>
<productid>800</productid>
</Product>
<Product>
<rowno>2</rowno>
<productid>900</productid>
</Product>
</Customer>
<Customer>
<Name>hij</Name>
<Product>
<rowno>1</rowno>
<productid>800</productid>
</Product>
<Product>
<rowno>2</rowno>
<productid>900</productid>
</Product>
</Customer>
</Wholesale>
abc
1.
800
2.
900
def
1.
800
2.
900
你好
1.
800
2.
900
这是XSLT,但我似乎无法在产品中添加rowno。请对将插入其中的XSLT转换发表评论
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- At the ExternalBidAwardCustomer element, copy everything and sub include ExternalBidAwardCustomer-->
<xsl:template match="Customer">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:copy-of select="../Product" />
</xsl:copy>
</xsl:template>
<xsl:template match='WholeSale'>
<WholeSale>
<xsl:apply-templates select="@*" />
<xsl:apply-templates select="Customer" />
</WholeSale>
</xsl:template>
<!-- Identity -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()[not(self::Product)]"/>
</xsl:copy>
</xsl:template>
有人能告诉我正确的方法吗?如何为此编写XSL?
谢谢您非常熟悉XSLT。您需要更改的主要内容是,的xsl:copy需要是xsl:apply模板,以便处理
产品
,然后将模板添加到process产品
以添加rowno
元素
下面是更新的XSLT。我添加了“DAN”注释以记录我所做的更改
小提琴手:我会采取不同的方法: XSLT1.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="*"/>
<xsl:template match="/Wholesale">
<xsl:copy>
<!-- collect all products ... -->
<xsl:variable name="products">
<xsl:for-each select="Product">
<xsl:copy>
<rowno>
<xsl:value-of select="position()"/>
</rowno>
<xsl:copy-of select="*"/>
</xsl:copy>
</xsl:for-each>
</xsl:variable>
<!-- ... and place them in each customer -->
<xsl:for-each select="Customer">
<xsl:copy>
<xsl:copy-of select="*"/>
<xsl:copy-of select="$products"/>
</xsl:copy>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
您尝试过什么(请将您的代码添加到您的问题中)?如果您需要一个起点…我要做的是从开始,并添加3个附加模板来覆盖身份转换。在第一个模板中,我将匹配/Wholesale
,并输出该元素(xsl:copy),并将模板应用于客户
。第二个模板将匹配Customer
,是身份模板(xsl:copy/xsl:apply templates部分),但也将模板应用于。/Product
。第三个模板将匹配Product
,也是标识模板,但使用xsl:number
添加rowno
元素。我能够转换,但是您能否指出如何在内部添加rownumber?如果您将代码添加到问题中,我可以添加显示如何添加行号的答案。添加了XSLT代码。Thanks@nextbond-很高兴听到!请通过点击旁边的复选标记来考虑接受这个答案(或者其他最好的答案,无论哪一个对你帮助最大)。谢谢