首页 > 解决方案 > 向 XSLT 1.0 中的非根节点添加新名称空间

问题描述

我看到了帖子XSLT : Add a namespace declaration to the root element

@StuartLC 答案有效。我需要帮助...在示例中@schglurps... ¿您如何将新命名空间添加到非根节点?

输入 XML 文档:

<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <DirectoryRef Id="AcquisitionFolder">
            <Directory Id="dir2EE87E668A6861A2C8B6528214144568" Name="bin" />
            <Directory Id="dir99C9EB95694B90A2CD31AD7E2F4BF7F6" Name="Decoders" />
        </DirectoryRef>
    </Fragment>
</Wix>

我想获得:

<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <DirectoryRef Id="AcquisitionFolder" xmlns:ns1="http://prerk">
            <Directory Id="dir2EE87E668A6861A2C8B6528214144568" Name="bin" />
            <Directory Id="dir99C9EB95694B90A2CD31AD7E2F4BF7F6" Name="Decoders" />
            <ns1:dir>prueba</ns1:dir>
        </DirectoryRef>
    </Fragment>
</Wix>

DirectoryRef节点(例如)中的新命名空间xmlns:ns1="http://prerk",它是非根并复制所有相同的节点。

我试过了,但我找不到任何合适的解决方案。

你能告诉我吗?

标签: xmlxsltxslt-1.0

解决方案


您可以使用以下方法获得预期结果:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"
exclude-result-prefixes="wix">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="wix:DirectoryRef">
     <DirectoryRef xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:ns1="http://prerk">
        <xsl:apply-templates select="@*|node()"/>
         <ns1:dir>prueba</ns1:dir>
    </DirectoryRef>
</xsl:template>

</xsl:stylesheet>

虽然这样做可能更简单:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"
exclude-result-prefixes="wix">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="wix:DirectoryRef">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <ns1:dir xmlns:ns1="http://prerk">prueba</ns1:dir>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

获得语义相同的结果:

<?xml version="1.0" encoding="utf-16"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Fragment>
    <DirectoryRef Id="AcquisitionFolder">
      <Directory Id="dir2EE87E668A6861A2C8B6528214144568" Name="bin" />
      <Directory Id="dir99C9EB95694B90A2CD31AD7E2F4BF7F6" Name="Decoders" />
      <ns1:dir xmlns:ns1="http://prerk">prueba</ns1:dir>
    </DirectoryRef>
  </Fragment>
</Wix>

推荐阅读