3

我正在尝试转换包含xmlns属性的另一个元素的子元素,但似乎我的转换被忽略,直到我删除xmlns.

所以假设我有:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          internalLogLevel="Trace"
          internalLogFile="NLogInternal.log"
          autoReload="true">
        <targets>
        </targets>
    </nlog>

我试图摆脱targets元素:

<nlog>
    <targets xdt:Transform="Remove" />
</nlog>

但这似乎不起作用,但是如果我删除xmlns并且xmlns:xsi属性转换按预期工作。

我做错了什么?

4

2 回答 2

1

我不知道这是否可行,但请尝试以下方法:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd">
    <targets xdt:Transform="Remove" />
</nlog>

通过将xmlns属性放在 上nlog,您可以指定您的目标是{http://www.nlog-project.org/schemas/NLog.xsd}nlog元素以及其中的{http://www.nlog-project.org/schemas/NLog.xsd}targets元素。

此外,您可能想对 XML 名称空间进行一些研究。

于 2015-04-07T17:04:34.570 回答
0

要删除targets元素,您需要考虑其命名空间。您可以在 XSLT 中使用前缀声明名称空间,您应该在模板匹配 XPath 表达式中使用它来消除targets树:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
    xmlns:ns1="http://www.nlog-project.org/schemas/NLog.xsd">

    <xsl:template match="@* | node()"> <!-- Copies all nodes to result tree -->
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="ns1:targets" /> <!-- Ignores this node -->

</xsl:stylesheet>

或者完全忽略命名空间。在这种情况下,您不必声明,但必须使用 XPath 表达式选择所有元素,但受其本地名称限制:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

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

    <xsl:template match="*[name()='targets']" />

</xsl:stylesheet>

我假设您发布的示例。如果您target在其他上下文和名称空间中有其他元素,您可能必须以不同的方式处理。

于 2015-04-07T16:45:30.390 回答