everydaylearn
everydaylearn

Reputation: 143

Remove newlines from a specific node of XML using XSLT

I have a node that is:

<item>
<name>abcd</name>
<type>pqrs</type>
</item>

I need to extract it to a new element as follows:

<newitem>
    <item>abcd</item>
    <completeXML>
          <item><name>abcd</name><type>pqrs</type></item>
    <completeXML>
</newitem>

The completeXML element will need to contain the entire source XML, but without line breaks. Thanks for any pointers.

Upvotes: 0

Views: 694

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117073

Not sure what difference it makes, but given the following input:

XML

<root>
   <color>
      <name>red</name>
      <type>primary</type>
   </color>
   <item>
      <name>abcd</name>
      <type>pqrs</type>
   </item>
   <shape>
      <name>circle</name>
      <type>2D</type>
   </shape>
</root>

the following stylesheet:

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="no"/>
<xsl:strip-space elements="item"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

will return:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <color>
      <name>red</name>
      <type>primary</type>
   </color>
   <item><name>abcd</name><type>pqrs</type></item>
   <shape>
      <name>circle</name>
      <type>2D</type>
   </shape>
</root>

Added:

WRT your edited question, try adding the following template:

<xsl:template match="/">
    <newitem>
        <xsl:text>&#10;&#9;</xsl:text>
        <item>abcd</item>
        <xsl:text>&#10;&#9;</xsl:text>
        <completeXML>
            <xsl:text>&#10;&#9;&#9;</xsl:text>
            <xsl:apply-templates/>
            <xsl:text>&#10;&#9;</xsl:text>
        </completeXML>
        <xsl:text>&#10;</xsl:text>
    </newitem>
</xsl:template>

Demo: http://xsltransform.net/jz1PuPR

Note that it's very unusual to want different indenting for some parts of the XML and, as a result, it requires a lot of work. And I am not at all convinced it's worth it.

Upvotes: 1

Related Questions