857 questions
How to handle missing nodes when producing flat XML
jn93
671
Reputation points
Hi All, I have XSLT to transform the complex XML to flat XML as per shown below. How can I fine tuning the XSLT coding below to ensure handle the missing nodes. Currently, for example below, the payment info nodes is missing for the OrderID=1. However, after I run XSLT the entire information for OrderID=1 is missing after transform. How can I get the expected output expected_ouput_flat_oder_xml.xml from the sample source order Order_xml.xml?
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Define the output method as XML and indent the output -->
<xsl:output method="xml" indent="yes"/>
<!-- Template matching the root element /Orders -->
<xsl:template match="/Orders">
<Orders>
<xsl:apply-templates select="Order"/> <!-- Apply templates to all Order elements -->
</Orders>
</xsl:template>
<!-- Template matching Order elements -->
<xsl:template match="Order">
<xsl:variable name="o" select="."/> <!-- Variable to hold the current Order node -->
<!-- Loop through OrderDetails/Detail/ShippedRemarks elements -->
<xsl:for-each select="$o/OrderDetails/Detail/ShippedRemarks"> <!-- Check if $o/OrderDetails/Detail/ShippedRemarks exists -->
<xsl:variable name="shr" select="."/> <!-- Variable to hold the current ShippedRemarks node -->
<xsl:variable name="d" select=".."/> <!-- Variable to hold the parent Detail node -->
<!-- Loop through ProductDetails/DetailName elements -->
<xsl:for-each select="$o/ProductDetails/DetailName">
<xsl:variable name="dn" select="."/> <!-- Variable to hold the current DetailName node -->
<!-- Loop through PaymentInfo elements -->
<xsl:for-each select="$o/PaymentInfo">
<xsl:variable name="pi" select="."/> <!-- Variable to hold the current PaymentInfo node -->
<!-- Output an Order element with the combined data -->
<Order>
<xsl:copy-of select="$o/OrderID | $o/CustomerID | $o/OrderDate"/> <!-- Copy values from the Order node -->
<xsl:copy-of select="$d/ProductID | $d/Quantity"/> <!-- Copy values from the parent DetailName node -->
<xsl:copy-of select="$shr/*"/> <!-- Copy values from the parent ShippedRemarks node -->
<xsl:copy-of select="$dn/*"/> <!-- Copy values from the current DetailName node -->
<xsl:copy-of select="$pi/*"/> <!-- Copy values from the current PaymentInfo node -->
</Order>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Developer technologies | XAML
Sign in to answer