简体   繁体   中英

Adding Namespace to header in XML

As per my initial requirement, I have written xslt code to remove namespace prefix from the code , but the namespace is also getting removed.

Below is the input file , output file and xslt code.

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<ns0:nfeProc xmlns:ns0="http://www.p.in.br/nf" versao="4.00">
<ns0:cUF>35</ns0:cUF>
<ns0:cNF>10131445</ns0:cNF>
</ns0:nfeProc>

transform.xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="*">
    <xsl:element name="{local-name(.)}">
      <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
  </xsl:template>
  <xsl:template match="@*">
    <xsl:attribute name="{local-name(.)}">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

Output:

<?xml version="1.0" encoding="UTF-8"?>
<nfeProc versao="4.00">
<cUF>35</cUF>
<cNF>10131445</cNF>
</nfeProc>

I also want to append n0 as namespace prefix for just nfeProc element and two namespaces inside it. Below is the desired output.

<?xml version="1.0" encoding="UTF-8"?>
<n0:nfeProc xmlns="http://www.p.in.br/nf" xmlns:n0="http://www.p.in.br/nf" versao="4.00">
<cUF>35</cUF>
<cNF>10131445</cNF>
</n0:nfeProc>

Please let me know what changes are required. Kindly help

Here's an XSLT 1.0 option, but like others have said, it doesn't make a whole lot of sense and may not work with all processors...

XML Input

<ns0:nfeProc xmlns:ns0="http://www.p.in.br/nf" versao="4.00">
<ns0:cUF>35</ns0:cUF>
<ns0:cNF>10131445</ns0:cNF>
</ns0:nfeProc>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:n0="http://www.p.in.br/nf" xmlns="http://www.p.in.br/nf">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|text()|comment()|processing-instruction()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/*">
        <n0:nfeProc>
            <xsl:apply-templates select="@*|node()"/>           
        </n0:nfeProc>
    </xsl:template>

    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

XML Output

<n0:nfeProc versao="4.00" xmlns:n0="http://www.p.in.br/nf" xmlns="http://www.p.in.br/nf">
<cUF>35</cUF>
<cNF>10131445</cNF>
</n0:nfeProc>

Fiddle (thanks @tim-c): http://xsltfiddle.liberty-development.net/3NJ3915/3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM