perfectxml.com
 Basic Search  Advanced Search   
Topics Resources Free Library Software XML News About Us
home » info bank » Ask perfectxml.com Team Tue, Aug 14, 2007
I am using XSLT to transform an XML document. I would like to copy a node in the resultant transformed document if it does not have a particular child node or has a child node with a particular value.
Let's look at an example.

The XSLT stylesheet in the following example uses xsl:if to see if count of child nodes named ChildNode is 0 or if this child node is present but it has an attribute printParentNode = 'yes'; only in such cases it prints the parent nodes.
Sample XML File (test.xml)
<?xml version="1.0" encoding="utf-8" ?> 
<Root>
  <ParentNode id="1"><ChildNode/></ParentNode>
  <ParentNode id="2"><ChildNode printParentNode="yes"/></ParentNode>
  <ParentNode id="3"><ChildNode printParentNode="no"/></ParentNode>
  <ParentNode id="4"/>
</Root>


XSLT stylesheet (test.xsl)
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" omit-xml-declaration="no" encoding="utf-8"/>

  <xsl:template match="/">
    <Root>
      <xsl:for-each select="/Root/ParentNode">
        <xsl:if test="count(ChildNode) &lt; 1 or ChildNode/@printParentNode = 'yes'">
          <ParentNode id="{@id}"><xsl:apply-templates/></ParentNode>
        </xsl:if>
      </xsl:for-each>
    </Root>
  </xsl:template>
  
</xsl:stylesheet>

  Contact Us | E-mail Us | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy