首页 > 解决方案 > 在 xml 根标签中添加命名空间

问题描述

这是我想在标题标签中添加命名空间的最少代码。这是我的输入 XML。任何人都可以帮助我。

<?xml version="1.0"?>
<R>
<M>
<H>1</H>
<B>
<p Ccy="GBP">1</p>
</B>
</M>
<M>
<H>1</H>
<B>
<p Ccy="GBP">4</p>
</B>
</M>

我试过这样

<?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
version="1.0" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

<xsl:output indent="yes" />

<xsl:template match="/*">
<R>
    <M>
        <xsl:apply-templates select="M[1]/H | M/B" />
    </M>
</R>
</xsl:template>

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

<xsl:template match="@*">
<xsl:copy/>
 </xsl:template>

</xsl:stylesheet> 

预期产出

<R xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03 Y:\Data\Dokument\Kommunikation\Layouter\ISO20022\Schema\Pain001\pain.001.001.03.xsd"> 
  <M> 
    <H>1</H> 
    <B> 
      <p Ccy="GBP">1</p> 
    </B> 
    <B> 
      <p Ccy="GBP">4</p> 
    </B> 
  </M>
</R>

小提琴https://xsltfiddle.liberty-development.net/ej9EGbG/41

标签: xmlxslt

解决方案


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="2.0" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

    <xsl:output indent="yes" />

    <xsl:template match="/*">
        <R xmlns:xsi="w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03 Y:\Data\Dokument\Kommunikation\Layouter\ISO20022\Schema\Pain001\pain.001.001.03.xsd">
            <M>
                <xsl:apply-templates select="M[1]/H | M/B" />
            </M>
        </R>
    </xsl:template>

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

    <xsl:template match="@*">
        <xsl:copy/>
    </xsl:template>
</xsl:stylesheet>
Chek it.

推荐阅读