xsl:copy-of排除父元素

8

我能用什么代码替代 <xsl:copy-of select="tag"/>,应用于以下XML时…


<tag>
  content
  <a>
    b
  </a>
</tag>

这句话的翻译是:“...会得到以下结果:?”
content
<a>
  b
</a>

我希望将其中所有内容回显,但不包括父标签。

基本上,我的 XML 文件中有几个以 HTML 格式排版的内容部分,分组在 XML 标签中。
我希望有条件地访问它们并将它们回显出来。
例如:<xsl:copy-of select="description"/>
生成的额外父标签不影响浏览器呈现,但它们是无效标签,我希望能够删除它们。
我这样做完全错误吗?

2个回答

12

由于您想要包含content部分,因此您需要使用node()函数,而不是*运算符:

<xsl:copy-of select="tag/node()"/>

我已在输入示例上进行了测试,结果与示例结果相同:

content
<a>
  b
</a>

不硬编码根节点名称,可以这样实现:

<xsl:copy-of select="./node()" />

在已经处理根节点的情况下,当你需要一个完全复制根节点内所有元素但不包括根节点本身时,这是非常有用的。例如:

<xsl:variable name="head">
  <xsl:copy-of select="document('head.html')" />
</xsl:variable>
<xsl:apply-templates select="$head" mode="head" />

<!-- ... later ... -->

<xsl:template match="head" mode="head">
  <head>
  <title>Title Tag</title>
  <xsl:copy-of select="./node()" />
  </head>
</xsl:template>

3

补充Welbog的答案,我赞同他的观点,建议按照以下方式编写单独的模板:

<xsl:template match="/">
  <body>
    <xsl:apply-templates select="description" />
  </body>
</xsl:template>

<xsl:template match="description">
  <div class="description">
    <xsl:copy-of select="node()" />
  </div>
</xsl:template>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接