Reputation: 895
I want to get the repeating "Author" element in the following XML structure against each product. How will i do it? I am using the following online tool for testing http://xslttest.appspot.com/
XML
<OrderDocument>
<OrderProduct>
<Product>
<ProductDescription>ProductDescription</ProductDescription>
<Author>Author</Author>
<Author>Author</Author>
</Product>
</OrderProduct>
<OrderProduct>
<Product>
<ProductDescription>ProductDescription</ProductDescription>
<Author>Author</Author>
<Author>Author</Author>
</Product>
</OrderProduct>
<OrderProduct>
<Product>
<ProductDescription>ProductDescription</ProductDescription>
<Author>Author</Author>
<Author>Author</Author>
</Product>
</OrderProduct>
</OrderDocument>
XSLT File:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="//OrderDocument">
</xsl:template>
</xsl:stylesheet>
Output Required:
<Message>
<Product>
<Author>Author</Author>
<Author>Author</Author>
</Product>
<Product>
<Author>Author</Author>
<Author>Author</Author>
</Product>
</Message>
Upvotes: 0
Views: 822
Reputation: 70618
For a transformation where you are not changing the entire XML document, you usually start off with the XSLT identity template
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
Then you only need to write templates for the nodes you do wish to transform. Looking at your input and expected output, there are three things you need to do
Rename the OrderDocument
element to Message
Remove the OrderProduct
element, but keep processing its children
Remove the ProductDescription
element entirely
Each of these can be achieve by a separate template. Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<!-- Rename OrderDocument to Message -->
<xsl:template match="OrderDocument">
<Message>
<xsl:apply-templates/>
</Message>
</xsl:template>
<!-- Remove OrderProduct, but keep processing its children -->
<xsl:template match="OrderProduct">
<xsl:apply-templates/>
</xsl:template>
<!-- Remove ProductDescription entirely -->
<xsl:template match="ProductDescription" />
<!-- Identity Template for everything else -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Upvotes: 4