我有一个输入XML,需要转换为下面给出的输出格式。我面临的问题是将确切的标签"IssuedList"复制到输出。因为我有一个for每个循环它不允许应用相同的变换。还有其他方法可以达到同样的效果吗?下面是我尝试过的XSLT
输入XML: <Books>
<Book>
<Id>1</Id>
<Name>ABC</Name>
<Categories RefId="1">
<Priority>High</Priority>
</Category>
</Categories>
<Categories RefId="2">
<Category>
<Priority>Low</Priority>
<Category>
</Categories>
<IssuedList>
<IssueList>
<Number>1</Number>
<Name>ABC</Name>
</IssueList>
<IssueList>
<Number>1</Number>
<Name>ABC</Name>
</IssueList>
</IssuedList>
</Book>
<Book>
<Id>2</Id>
<Name>DEF</Name>
<Categories RefId="1">
<Category>
<Priority>High</Priority>
</Category>
</Categories>
<Categories RefId="2">
<Category>
<Priority>Low</Priority>
</Category>
</Categories>
<IssuedList>
<IssueList>
<Number>1</Number>
<Name>DEF</Name>
</IssueList>
</IssuedList>
</Book>
并希望看到转换后的输出为
<Books>
<Book>
<Id>1</Id>
<Name>ABC</Name>
<RefId>1</RefId>
<Priority>High</Priority>
<IssuedList>
<IssueList>
<Number>1</Number>
<Name>ABC</Name>
</IssueList>
<IssueList>
<Number>1</Number>
<Name>ABC</Name>
</IssueList>
</IssuedList>
</Book>
<Book>
<Id>1</Id>
<Name>ABC</Name>
<RefId>2</RefId>
<Priority>Low</Priority>
<IssuedList>
<IssueList>
<Number>1</Number>
<Name>ABC</Name>
</IssueList>
<IssueList>
<Number>1</Number>
<Name>ABC</Name>
</IssueList>
</IssuedList>
</Book>
<Book>
<Id>2</Id>
<Name>DEF</Name>
<RefId>1</RefId>
<Priority>High</Priority>
<IssuedList>
<IssueList>
<Number>1</Number>
<Name>DEF</Name>
</IssueList>
</IssuedList>
</Book>
<Book>
<Id>2</Id>
<Name>DEF</Name>
<RefId>2</RefId>
<Priority>Low</Priority>
<IssuedList>
<IssueList>
<Number>1</Number>
<Name>DEF</Name>
</IssueList>
</IssuedList>
</Book>
</Books>
我将XSLT写成如下
<xsl:for-each select ="/Books/Book">
<xsl:variable name="Id" select ="Id"></xsl:variable>
<xsl:variable name="Name" select ="Name"></xsl:variable>
<xsl:for-each select ="Categories/Category">
<Book>
<RefId>
<xsl:value-of select ="@RefId"></xsl:value-of>
</RefId>
<Id>
<xsl:value-of select ="$Id"></xsl:value-of>
</Id>
<Name>
<xsl:value-of select ="$Name"></xsl:value-of>
</Name>
</Book>
</xsl:for-each>
</xsl:for-each>
我觉得你把事情弄得太复杂了。试一试:
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:template match="/">
<Books>
<xsl:for-each select ="Books/Book/Category">
<Book>
<xsl:copy-of select ="../Id"/>
<xsl:copy-of select ="../Name"/>
<RefId><xsl:value-of select ="@RefId"/></RefId>
<xsl:copy-of select ="Priority"/>
<xsl:copy-of select ="../IssuedList"/>
</Book>
</xsl:for-each>
</Books>
</xsl:template>
</xsl:stylesheet>