0

Given the following XML:

<?xml version="1.0" encoding="utf-8"?>
<Store>
  <p1:Document xmlns:p1="urn:iso:std:iso:xyz">
    <p1:Class>
      Hello
      <p1:Type>
        Now
      </p1:Type>
    </p1:Class>
    <!-- more elements -->
  </p1:Document>
</Store>

How would I write an XSLT to transform the Document element in the following way:

<?xml version="1.0" encoding="utf-8"?>
<Store>
  <Document xmlns="urn:iso:std:iso:123>
    <Class>
      Hello
      <Type>
        Now
      </Type>
    </Class>
    <!-- more elements -->
  </Document>
</Store>

As you can see, I need to copy the Document element, but I need to strip all of its namespace declarations and prefixes, and then add a new namespace declaration.

How would I accomplish this in XSL?

Infin8Loop
  • 284
  • 3
  • 14

1 Answers1

0

The solution is a variation of an answer like
"How to remove namespace prefix leaving namespace value (XSLT)?" and the application of a template with a mode attribute to process only the children of the Document element.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:p1="urn:iso:std:iso:xyz" version="1.0">
  <xsl:output indent="yes" method="xml" />
  <xsl:variable name="replacementNamespace" select="'urn:iso:std:iso:123'" />

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

  <!-- template to replace namespace -->
  <xsl:template match="*" mode="newNamespace">
    <xsl:element name="{local-name()}" namespace="{$replacementNamespace}">
      <xsl:apply-templates select="@*|node()" mode="newNamespace" />
    </xsl:element>
  </xsl:template>

  <!-- template to process Document element -->
  <xsl:template match="p1:Document">
    <xsl:apply-templates select="." mode="newNamespace" />
  </xsl:template>

</xsl:stylesheet>

If you still get unwanted namespaces in the output document, follow the instructions in the answer "XSL: Avoid exporting namespace definitions to resulting XML documents" and add exclude-result-prefixes="ns0 ns1" to your xsl:stylesheet element. This should get rid of some unwanted namespaces quite easily.

If this doesn't help, you need to create a new question with a Minimal, Complete and Verifiable Example containing all relevant aspects.


Next time at least try to solve the problem on your own by searching this site for answers.

zx485
  • 28,498
  • 28
  • 50
  • 59
  • I am trying, but still hitting roadblocks. Latest roadblock as a question: https://stackoverflow.com/questions/51524370/how-do-i-prevent-xml-namespaces-from-being-injected-into-my-xsl-output – Infin8Loop Jul 25 '18 at 17:29
  • works great in my xml editor, but when I run it though the Java XSLT transformer, it outputs like this: etc... – Infin8Loop Jul 25 '18 at 18:50