我有一个 XML 文件,我想使用 XSLT 复制一些元素,但它在复制的元素中添加 xmlns=" " 。
XSLT
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://www.example.com/rsd/DataAccess"
exclude-result-prefixes="x"
>
<xsl:output method="xml" indent="yes"/>
<!-- Identity transform -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="x:Adapter[@Key='AuditLogging']">
<xsl:copy-of select="."/>
<Adapter Key="AutoExport"></Adapter>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
XML
<Adapters xmlns="http://www.example.com/rsd/DataAccess">
<Adapter Key="LASTCHANGEDATE" />
<Adapter Key="AuditLogging" />
</Adapters>
Run Code Online (Sandbox Code Playgroud)
输出 XML
<Adapters xmlns="http://www.example.com/rsd/DataAccess">
<Adapter Key="LASTCHANGEDATE" />
<Adapter Key="AuditLogging" />
<Adapter Key="AutoExport" xmlns="" />
</Adapters>
Run Code Online (Sandbox Code Playgroud)
如何防止在元素中添加 xmlns=" "
这是因为在您的输入 XML 中,所有元素都属于一个命名空间
<Adapters xmlns="http://www.example.com/rsd/DataAccess">
Run Code Online (Sandbox Code Playgroud)
Adapter但是,当您在模板中创建新元素时,就像这样......
<Adapter Key="AutoExport">
Run Code Online (Sandbox Code Playgroud)
您实际上正在创建一个不属于任何名称空间的新元素,因此输出会xmlns=''表明这一点。
一种解决方案是在 XSLT 中声明默认名称空间,以便您在 XSLT 中创建的任何无前缀元素都将成为该名称空间的一部分。
试试这个 XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://www.example.com/rsd/DataAccess"
xmlns="http://www.example.com/rsd/DataAccess" exclude-result-prefixes="x">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="x:Adapter[@Key='AuditLogging']">
<xsl:copy-of select="."/>
<Adapter Key="AutoExport" />
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2111 次 |
| 最近记录: |