首页 > 解决方案 > xslt 中的规范化空间

问题描述

当我们在 xslt 中使用标准化空间时,子元素/标签会被自动删除。如果我不想删除特定的子标签,那么我应该使用什么?

代码:

<mixed-citation publication-type="book">
<collab>Panel on Antiretroviral Guidelines for Adults and Adolescents</collab>
. 
<source>
Guidelines for the use of antiretroviral agents in HIV-1-infected adults and adolescents
</source>
. 
<publisher-loc>Rockville, MD</publisher-loc>
 : 
<publisher-name>US Department of Health and Human Services (DHHS)</publisher-name>; May 
<year>2014</year> [regularly updated]. [
<uri xlink:href="http://aidsinfo.nih.gov/guidelines/html/1/adult-and-adolescent-arv-guidelines/0">URL</uri>]
</mixed-citation>
</ref>

XSLT 代码:

<xsl:template match = "mixed-citation">
<xsl:element name = "p">
<xsl:value-of select="normalize-space()"/>
</xsl:element>
</xsl:template>

在上面的代码中,我想打印所有文本值并删除除 <uri> 标签之外的所有标签。请帮忙 !!!

标签: xslt

解决方案


如果您想跳过后代元素并复制某个元素,那么您有两个选择,使用xsl:mode on-no-match="shallow-skip"默认值,然后为uri要复制的元素编写模板:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

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

  <xsl:template match="mixed-citation">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="mixed-citation//text()">
      <xsl:value-of select="normalize-space()"/>
  </xsl:template>

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

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/eiZQaFi

shallow-copy用作默认值,然后确保将其覆盖descendantsuri

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

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

  <xsl:template match="mixed-citation">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="mixed-citation//text()">
      <xsl:value-of select="normalize-space()"/>
  </xsl:template>

  <xsl:template match="mixed-citation//*[not(self::uri)]">
      <xsl:apply-templates/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/eiZQaFi/1

如果您使用的是早期版本,那么当前版本 3 的 XSLT 然后请参阅https://www.w3.org/TR/xslt-30/#built-in-templates-shallow-skip以了解使用的xsl:mode声明如何转换为模板,例如代替

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

您可以使用

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

shallow-copy转换为众所周知的身份转换模板。


推荐阅读