user3114844
user3114844

Reputation: 21

Use XSLT to copy XML without the xml declaration

I have the following xml and want the output to not contain the xml declaration i.e.

FROM

 <?xml version="1.0" encoding="UTF-8"?>
 <tns:MFTRNS xmlns:tns="MFTRNS" recordState="New" msgVersion="13.0">
 <OSCONO>100</OSCONO>
 <OSINOU>1</OSINOU>
 <OSDLIX>155379</OSDLIX>
 <OSPANR>AAG44780</OSPANR>
 <OSWHLO>AAG</OSWHLO>
 </tns:MFTRNS>

TO

 <tns:MFTRNS xmlns:tns="MFTRNS" recordState="New" msgVersion="13.0">
 <OSCONO>100</OSCONO>
 <OSINOU>1</OSINOU>
 <OSDLIX>155379</OSDLIX>
 <OSPANR>AAG44780</OSPANR>
 <OSWHLO>AAG</OSWHLO>
 </tns:MFTRNS>

Can you get an xslt to do this and if so how?

The reason for doing this is that I want to wrap the xml in an envelope which cannot be done if the declaration is a part of the XML as it does not create a valid xml file

Thanks

Upvotes: 2

Views: 1195

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122364

If you only want to remove the declaration then a stylesheet as simple as this will do it:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" omit-xml-declaration="yes" />

  <xsl:template match="/">
    <xsl:copy-of select="node()" />
  </xsl:template>
</xsl:stylesheet>

But if your ultimate aim is to "wrap the xml in an envelope" then you might be better doing that directly in your XSLT, for example:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" />

  <xsl:template match="/">
    <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope">
      <xsl:copy-of select="node()" />
    </soap:Envelope>
  </xsl:template>
</xsl:stylesheet>

which will be safer than trying to combine the two files using non-XML-aware textual operations. For example, if your envelope declares a default namespace xmlns="http://example.com" then simply inserting the text of another XML document inside the envelope would change the semantics as it would move the non-prefixed elements like OSCONO into the envelope's default namespace when they should really be in no namespace. XSLT will spot this case and add the necessary xmlns="" overrides.

Upvotes: 3

Carlo Cannas
Carlo Cannas

Reputation: 3262

It's simple: you have to set the omit-xml-declaration attribute of your xsl:output element to yes.

Upvotes: 0

Related Questions