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

XSLT:如何从xml字符串中排除某些html标签?

发布时间:2020-12-16 22:55:51 所属栏目:百科 来源:网络整理
导读:我正在尝试使用XSLT 1.0从xml字符串中排除某些html标记集 在这里,目前我排除 a和 img标签.对于 a标签,我想只显示文字. 尝试过的XSLT模板: xsl:template match="*" mode="ExcludeHTMLTags" xsl:choose xsl:when test="local-name() = 'a' or local-name() =
我正在尝试使用XSLT 1.0从xml字符串中排除某些html标记集

在这里,目前我排除< a>和< img>标签.对于< a>标签,我想只显示文字.

尝试过的XSLT模板:

<xsl:template match="*" mode="ExcludeHTMLTags">
  <xsl:choose>
    <xsl:when test="local-name() = 'a' or local-name() = 'img'">
      <xsl:value-of select="text()"/>
    </xsl:when>
    <xsl:otherwise>
  <xsl:apply-templates select="node()|@*"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

以下面的方式调用上面的模板:

<xsl:variable name="guideContent">
  <root>
    <xsl:apply-templates 
 select="document(@guideID)/tcm:Component/tcm:Data/tcm:Content/em:GeneralContent/em:Body/node()" 
 mode="expandXHTML"/>
  </root>
</xsl:variable>
<xsl:apply-templates select="msxsl:node-set($guideContent)/node()" mode="ExcludeHTMLTags"/>

输入XML字符串:

<root>
This is a test message.
<p>Message within p tag</p> click <a href="www.test.com">here</a>.
<img src="/test.jpg" /> Message after image.
<strong>Message within strong</strong>
<link:component id="XXX" ... >My Link</link:component>
<p>Message after link component</p>
</root>

OUTPUT:

<root>
This is a test message.
<p>Message within p tag</p> click here.
Message after image.
<strong>Message within strong</strong>
<link:component id="XXX" ... >My Link</link:component>
<p>Message after link component</p>
</root>

请告诉我我做错了什么,并告诉最好的方法.

解决方法

这种转变:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="a"><xsl:apply-templates/></xsl:template>
 <xsl:template match="img"/>
</xsl:stylesheet>

当应用于此XML文档时(没有由OP提供!!!):

<html>
 <body>
  <a>Anchor text</a>
  <img source="http://someUrl"/>
 </body>
</html>

产生想要的,正确的结果:

<html>
   <body>Anchor text</body>
</html>

(编辑:李大同)

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

    推荐文章
      热点阅读