首页 > 解决方案 > 将命名空间添加到 XML 中的标头

问题描述

根据我最初的要求,我编写了 xslt 代码以从代码中删除命名空间前缀,但命名空间也被删除了。

下面是输入文件、输出文件和 xslt 代码。

输入.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>

变换.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>

输出:

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

我还想为 nfeProc 元素和其中的两个命名空间附加 n0 作为命名空间前缀。以下是所需的输出。

<?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>

请让我知道需要进行哪些更改。请帮助

标签: xmlxslt

解决方案


这是一个 XSLT 1.0 选项,但就像其他人所说的那样,它没有多大意义,并且可能不适用于所有处理器......

XML 输入

<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 输出

<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>

小提琴(感谢@tim-c):http: //xsltfiddle.liberty-development.net/3NJ3915/3


推荐阅读