简体   繁体   English

如何获取节点的内容并保留内部标签

[英]How to get contents of a node and preserve inner tags

Using XSLT, given something like this: 使用XSLT,如下所示:

<summary>
    Blah, blah, blah <code>foo</code> blah <code>bar</code> blah.
</summary>

How would you transform it into something like: 您将如何将其转换为类似以下内容:

<div>
    Blah, blah, blah <code>foo</code> blah <code>bar</code> blah.
<div>

I started out, in my XSLT, with something like: 我在XSLT中以类似以下内容开始:

<div>
    <xsl:value-of select="summary"/>
</div>

But this will transform into: 但这将变成:

<div>
    Blah, blah, blah foo blah bar blah.
<div>

In other words, I lost the inner <code> . 换句话说,我丢失了内部的<code> I then tried 然后我尝试了

<div>
    <xsl:copy-of select="summary"/>
</div>

But that'll give me: 但这会给我:

<div>
    <summary>
        Blah, blah, blah <code>foo</code> blah <code>bar</code> blah.
    </summary>
</div>

In other words, the <summary> tag that I aimed to replace is included. 换句话说,包含了我打算替换的<summary>标记。

Then I started getting creative: 然后我开始变得很有创意:

<xsl:copy-of select="summary/*"/>

Only outputs the contents of the <code> tags 仅输出<code>标记的内容

<xsl:copy-of select="summary/text()"/>

Removes the <code> tags and their contents entirely. 完全删除<code>标记及其内容。

So is there a way to make this work? 那么有没有办法使这项工作呢? Select the contents of the summary tag (without the summary tag itself) and preserve any inner tags? 选择summary标签的内容(没有summary标签本身)并保留任何内部标签?

If you want to transform the summary element into a div then write a template doing that 如果要将summary元素转换为div编写一个模板

  <xsl:template match="summary">
      <div>
          <xsl:apply-templates/>
      </div>
  </xsl:template>

Then you only need to make sure the rest is copied unchanged which you can do in XSLT 3 ( http://xsltfiddle.liberty-development.net/eiQZDba ) with 然后,您只需要确保其余部分保持不变即可复制,您可以在XSLT 3( http://xsltfiddle.liberty-development.net/eiQZDba )中使用

  <xsl:mode on-no-match="shallow-copy"/>

or in earlier versions by spelling out the identity transformation as a template 或在较早版本中,通过将身份转换作为模板进行说明

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

Use an identity template and a replace template with xsl:apply-templates inside like this: 使用身份模板和内部带有xsl:apply-templates的替换模板,如下所示:

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

<!-- replace template - more specific element template -->
<xsl:template match="summary">
  <div>
    <xsl:apply-templates select="node()|@*" />
  </div>
</xsl:template>

Result: 结果:

<div>
    Blah, blah, blah <code>foo</code> blah <code>bar</code> blah.
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM