XSLT - 为命名空间添加前缀

时间:2021-04-16 21:34:11

标签: xslt

这是我的输入 XML:

<?xml version="1.0" encoding="UTF-8"?>
<Sync
    xmlns="http://schema.infor.com/InforOAGIS/2" languageCode="en-US" versionID="2.8.0">
    <Data>
        <ID>0001</ID>
        <Text>ABCD</Text>
    </Data>
</Sync>

这是我的预期结果:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:Sync xmlns:ns0="http://schema.infor.com/InforOAGIS/2"
      languageCode="en-US"
      versionID="2.8.0">
      <DataArea xmlns:dns="http://schema.infor.com/InforOAGIS/2" xmlns="">
      <ID>0001</ID>
      <Text>ABCD</Text>
   </DataArea>
</ns0:Sync>

我当前的 XSLT 如下 (https://xsltfiddle.liberty-development.net/nbiE19N)。 有两个问题:

  1. 我在 DataArea 元素中有额外的 xmlns=""。我只想添加 dns 命名空间。
  2. 我无法为我的命名空间添加 ns0 前缀
<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/*:Sync">
        <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="/*:Sync/*:Data">
        <DataArea>
            <xsl:namespace name="dns" select="'http://schema.infor.com/InforOAGIS/2'"/>
            <ID>
                <xsl:value-of select="/*:Sync/*:Data/*:ID"/>
            </ID>
            <Text>
                <xsl:value-of select="/*:Sync/*:Data/*:Text"/>
            </Text>
        </DataArea>
    </xsl:template>
</xsl:stylesheet>

感谢任何建议!

1 个答案:

答案 0 :(得分:0)

这是否返回了预期的结果:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://schema.infor.com/InforOAGIS/2">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Sync">
    <ns0:Sync xmlns:ns0="http://schema.infor.com/InforOAGIS/2">
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates/>
    </ns0:Sync> 
</xsl:template>

<xsl:template match="Data">
    <DataArea xmlns:dns="http://schema.infor.com/InforOAGIS/2">
        <xsl:apply-templates/>
    </DataArea> 
</xsl:template> 

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

</xsl:stylesheet>

附言我不确定您为什么需要 xmlns:dns="http://schema.infor.com/InforOAGIS/2" 声明;它没有在任何地方使用。