加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – 如何在Xslt中将节点名替换为另一个?

发布时间:2020-12-16 07:57:20 所属栏目:百科 来源:网络整理
导读:对这个问题说不好,对不起.将尝试解释我正在尝试做什么. 基本上我将搜索的输出作为Xml,在Xml中有一个像这样的节点: FIELD NAME="body" Somebody named keyDoris/key and keyArnie/key /FIELD 简而言之,我需要的是替换“ key”用“ strong”;即.突出显示搜索
对这个问题说不好,对不起.将尝试解释我正在尝试做什么.
基本上我将搜索的输出作为Xml,在Xml中有一个像这样的节点:
<FIELD NAME="body">
  Somebody named 
  <key>Doris</key> 
  and 
  <key>Arnie</key> 
</FIELD>

简而言之,我需要的是替换“< key>”用“< strong>”;即.突出显示搜索命中(关键节点值是用户搜索的内容).在Xslt我不知道用户搜索了什么,除了查询Xml – >技术领域[@名称= ‘体’] /键.

现在我有一些疯狂的代码将提取搜索词前面的任何内容(“Doris”),但是这个代码适用于1个搜索词.我们需要它来执行多个术语.我们使用的代码如下所示:

<xsl:template name="highlighter">
    <xsl:param name="text"/>
    <xsl:param name="what"/>

    <xsl:choose>
      <xsl:when test="contains($text,$what) and string-length($what) &gt; 0">
        <xsl:variable name="before" select="substring-before($text,$what)"/>
        <xsl:variable name="after" select="substring-after($text,$what)"/>
        <xsl:variable name="real-before" select="substring($text,1,string-length($before))"/>
        <xsl:variable name="real-what" select="substring($text,string-length($before) + 1,string-length($what))"/>
        <xsl:variable name="real-after" select="substring($text,string-length($before) + string-length($what) + 1)"/>
        <xsl:value-of select="$real-before"/>

        <strong>
          <xsl:value-of select="$real-what"/>
        </strong>

        <xsl:call-template name="highlighter">
          <xsl:with-param name="text" select="$real-after"/>
          <xsl:with-param name="what" select="$what"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

我一直试图做的是用不同的搜索术语多次调用这段代码,但我正在考虑如何使用调用模板的输出作为下一次调用的输入.在代码中它将是这样的:

string body = doc.SelectSingleNode("FIELD[@NAME='body']");
NodeCollection nodes = doc.SelectNodes("FIELD[@NAME='body']/key");
foreach (var node in nodes) {
    body = hightlighter(body,node.InnerText);   
}

到目前为止,我一直无法在XSLT中做这样的事情,但我仍然是一个菜鸟所以……;)

编辑:只是为了澄清;我正在寻找的输出是这样的:

Somebody named <strong>Doris</strong> and <strong>Arnie</strong>
在这种情况下,最好的做法是递归地将节点从输入复制到输出,并覆盖要以不同方式处理的节点.关键思想是文本字符串是可以复制的节点.这是一个例子:
<xsl:template match="key">
    <strong>
        <xsl:apply-templates select="@*|node()"/>
    </strong>
</xsl:template>

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读