使用 xslt 删除特定元素开头的 Space 或 spaces 和文本之间的连续 space

Removing Space or spaces in the starting of the specific element and consecutive space in between text using xslt

我想删除连续的 spaces 到单个 space 并且在打开或关闭特定元素之前或之前 space 或 spaces 需要删除而不影响子元素。

输入:

<products>
<product1> Product P  <i>Product</i> Q</product1>
<product1> </product1>
<product2>  Product <b>Q Product R</b>   </product2>
<product2><b></b></product2>
<product3>Product  R  </product3>
<product4> Product S </product4>
<product5>Product T </product5>
</products>

XSLT 尝试过:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>
    
    <xsl:template match="*">
       <xsl:copy>
         <xsl:copy-of select="@*"/>
         <xsl:apply-templates/>
       </xsl:copy>
    </xsl:template>

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

输出:

<products>
   <product1>Product P<i>Product</i>Q
   </product1>
   <product2>Product<b>Q Product R</b></product2>
   <product3>Product R</product3>
   <product4>Product S</product4>
   <product5>Product T</product5>
</products>

所需输出:

<products>
<product1>Product P <i>Product</i> Q</product1>
<product2>Product <b>Q Product R</b></product2>
<product3>Product R</product3>
<product4>Product S</product4>
<product5>Product T</product5>
</products>

请指教。 提前致谢。

我不认为从一个例子中可以清楚地看出规则,但是

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

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

  <xsl:template match="products/*/text()[not(following-sibling::node()[self::*]) and not(preceding-sibling::node()[self::*])]">
      <xsl:value-of select="normalize-space()"/>
  </xsl:template>
  
  <xsl:template match="products/*/text()[preceding-sibling::node()[self::*]]">
      <xsl:value-of select=". => replace('\s+$', '') => replace('\s+', ' ')"/>
  </xsl:template>
  
    <xsl:template match="products/*/text()[following-sibling::node()[self::*]]">
      <xsl:value-of select=". => replace('^\s+', '') => replace('\s+', ' ')"/>
  </xsl:template>
   
</xsl:stylesheet>

更接近您想要的结果,所以如果您的需求很明确,也许您可​​以调整它。

https://xsltfiddle.liberty-development.net/93nwMoc