【问题标题】:XSLT: How to exclude certain html tags from xml string?XSLT:如何从 xml 字符串中排除某些 html 标签?
【发布时间】:2012-10-11 02:45:01
【问题描述】:

我正在尝试使用 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>

输出:

<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>

请提出我做错了什么并告诉最好的方法。

【问题讨论】:

  • 请提供源 XML 文档和所需的确切结果。
  • @DimitreNovaatchev:我已经更新了示例输入和预期输出。
  • Siva Charan -- 这又是非常畸形的。无论如何,我已经使用格式良好的 (x)Html 回答了您的问题。
  • @DimitreNovaatchev:为了形成良好的格式,我可以包装一个根节点。所以我猜不会有问题。
  • Siva Charan,它的格式仍然不正确——你没有合适的 XML 编辑器/IDE 可以立即看到吗?

标签: xslt tridion


【解决方案1】:

这种转变

<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>

【讨论】:

  • 我有一个疑问,实际上我已经在使用node()|@* 模板匹配进行初始检查。现在我不能使用相同的匹配。有没有办法解决这个问题?
  • @SivaCharan,请复制并粘贴这段代码并运行它——这是验证它是否正常工作的最简单、最直接的方法。
  • 谢谢迪米特。它似乎按预期工作。我已经根据您的输入更改了我的模板,现在正在对其进行测试。一旦我完成了所有的测试,我会更新状态给你并接受答案。
猜你喜欢
  • 2012-08-07
  • 1970-01-01
  • 2014-07-26
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多