Changing namespace position in XML between elements

29 views Asked by At

Source XML

<Message xmlns="urn:teams:1">
  <Header>
     <Source>center</Source>
  </Header>
<row>
<Events xmlns="urn:teams:2">
<Event>
<createdDateTime>2023-01-06T09:42:11-06:00</createdDateTime>
<name>Houston</name>
<Details>
<value>serial number 327</value>
</Details>
</Event>
</Events>
</row>
</Message>

Output XML which is required

<Message xmlns="urn:teams:1">
<Header>
<Source>center</Source>
</Header>
<row>
<Events>
<Event  xmlns="urn:teams:2">
<createdDateTime>2023-01-06T09:42:11-06:00</createdDateTime>
<name>Houston</name>
<Details>
<value>serial number 327</value>
</Details>
</Event>
</Events>
</row>
</Message>

I tried different combinations of XSLT but not getting the Output XML. Please help me to code the XSLT.

Thanks

I tried XSLT like below and different flavors of it but not getting the result

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="urn:teams:1"   xmlns:ns1="urn:teams:2">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*" >
        <xsl:element name="{local-name()}" namespace="urn:teams:1">
            <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
    </xsl:template>
<xsl:template match="/ns0:Message/ns0:row/ns0:Events/ns1:Event">
        <xsl:element name="Event" xmlns="urn:teams:2">
        <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>
1

There are 1 answers

0
Heiko Theißen On BEST ANSWER

Solution with XSLT 1.0:

You need only change the namespace of the <Events> element. To match this element, a namespace prefix t2 is introduced, but this is excluded from the output with exclude-result-prefixes.

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
  xmlns:t2="urn:teams:2"
  exclude-result-prefixes="t2">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="t2:Events">
    <Events xmlns="urn:teams:1">
      <xsl:apply-templates select="@*|node()" />
    </Events>
  </xsl:template>
</xsl:stylesheet>