如何在xslt从html到xml的转换中将文本和某个元素的元素节点分成两部分而不丢失标记?

问题描述 投票:0回答:1
xslt
1个回答
0
投票

解决方法如下:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  expand-text="yes">

  <xsl:output method="html" indent="no" html-version="5"/>

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

  <xsl:template match="p">
    <xsl:variable name="markers" as="element(p)">
      <xsl:apply-templates select="." mode="markers"/>
    </xsl:variable>
    <xsl:apply-templates select="$markers" mode="wrap"/>
  </xsl:template>
  
  <xsl:template mode="markers" match="p//text()">
    <xsl:apply-templates select="analyze-string(., '\.')" mode="analyze"/>
  </xsl:template>
  
  <xsl:template mode="analyze" match="*:match">
    <dot/>
  </xsl:template>
  
  <xsl:template mode="wrap" match="p">
    <PARA>
      <xsl:for-each-group select="node()" group-ending-with="dot">
        <xsl:choose>
          <xsl:when test="position() = 2">
            <x>
              <xsl:apply-templates select="current-group()"/>
            </x>
          </xsl:when>
          <xsl:when test="position() = 3">
            <y>
              <xsl:apply-templates select="current-group()"/>
            </y>
          </xsl:when>
          <xsl:otherwise>
            <xsl:apply-templates select="current-group()"/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:for-each-group>
    </PARA>
  </xsl:template>
  
  <xsl:template match="dot"/>
  
  <xsl:template match="i">
    <EMPHASIS>
      <xsl:apply-templates/>
    </EMPHASIS>
  </xsl:template>

  <xsl:template match="sub">
    <SUBSCRIPT>
      <xsl:apply-templates/>
    </SUBSCRIPT>
  </xsl:template>
  
  <xsl:template match="/" name="xsl:initial-template">
    <xsl:copy>
      <xsl:apply-templates/>
      <xsl:comment>Run with {system-property('xsl:product-name')} {system-property('xsl:product-version')} at {current-dateTime()}</xsl:comment>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

在线小提琴.

© www.soinside.com 2019 - 2024. All rights reserved.