Sonam Daultani
Sonam Daultani

Reputation: 749

Get xml node child together with xml tags

I have the following input xml

<?xml version="1.0" encoding="UTF-8"?>  
<Parent>  
  <ParentElement1>PE1</ParentElement1>  
  <ParentElement2>PE2</ParentElement2>  
  <Child>  
    <ChildElement1>CE1</ChildElement1>  
    <ChildElement2>CE2</ChildElement2>  
  </Child>  
</Parent>

I need to extract Child present inside Parent,

Output must look like :

<Child>  
  <ChildElement1>CE1</ChildElement1>  
  <ChildElement2>CE2</ChildElement2>  
</Child>`

I have tried with XPath expression /Parent/Child, but it selects text only CE1 & CE2.

Upvotes: 1

Views: 118

Answers (1)

kamituel
kamituel

Reputation: 35950

The key here is to use <xsl:copy-of> instead of <xsl:value-of>.

From the XSL spec: The xsl:copy-of element can be used to copy a node-set over to the result tree without converting it to a string..

Use the following stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" />
<!-- To get rid of <?xml ... declaration, use the following:
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes" /> -->

<xsl:template match="/">
  <!-- use copy-of instead of value-of -->
  <xsl:copy-of select="/Parent/Child" />
</xsl:template>

</xsl:stylesheet>

Output:

<?xml version="1.0" encoding="UTF-8"?>
<Child>
   <ChildElement1>CE1</ChildElement1>
   <ChildElement2>CE2</ChildElement2>
</Child>

Upvotes: 1

Related Questions