【问题标题】:Analyze text() node and add new nodes in XSLT分析 text() 节点并在 XSLT 中添加新节点
【发布时间】:2015-11-19 09:36:27
【问题描述】:

我正在使用 XSLT 进行 html 到 xml 的转换,在 html 输入中我有如下内容,

<p>An image outside a paragraph is placed into an <em>Element Image Frame</em>. If there are no (or not enough) <em>Element Image Frames</em> then the image is ignored and a warning is logged.</p>

使用 xsl,我需要的是,如果&lt;em&gt; 节点之前或之后有空格,这些节点应该替换为,&lt;space/&gt; 节点。所以预期的输出,

<p>An image outside a paragraph is placed into an<space/><Italic>Element Image Frame</Italic>. If there are no (or not enough)<space/><Italic>Element Image Frames</Italic><space/>then the image is ignored and a warning is logged.</p>

注意第一个&lt;em&gt;节点后面没有空格,所以没有添加&lt;space/&gt;

我想我可以使用 XSLT 正则表达式,但我正在努力编写一个在 &lt;em&gt; 节点之前和之后选择两个空格的正则表达式。

<xsl:template match="p/text()">
        <xsl:analyze-string select="." regex="^(&#x20;)">
            <xsl:matching-substring>
                <xsl:choose>
                    <xsl:when test="regex-group(1)">
                        <space/>
                    </xsl:when>                
                </xsl:choose>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>

谁能给我建议一个方法来做到这一点..

【问题讨论】:

    标签: xml xslt xslt-2.0


    【解决方案1】:

    由于可以使用starts-with 和/或ends-with 检查条件,但也涉及某个同级元素的存在,我将简单地编写具有匹配模式的模板:

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:template match="@* | node()">
      <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
    </xsl:template>
    
    <xsl:template match="em">
      <Italics>
        <xsl:apply-templates select="@* | node()"/>
      </Italics>
    </xsl:template>
    
    <xsl:template match="p/text()[starts-with(., ' ') and preceding-sibling::node()[1][self::em]]">
       <space/>
       <xsl:value-of select="substring(., 2)"/>
    </xsl:template>
    
    <xsl:template match="p/text()[ends-with(., ' ') and following-sibling::node()[1][self::em]]">
       <xsl:value-of select="substring(., 1, string-length() - 1)"/>
       <space/>
    </xsl:template>
    
    <xsl:template match="p/text()[starts-with(., ' ') and preceding-sibling::node()[1][self::em] and
                                  ends-with(., ' ') and following-sibling::node()[1][self::em]]" priority="5">
       <space/>
       <xsl:value-of select="substring(., 2, string-length() - 1)"/>
       <space/>
    </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

      【解决方案2】:

      正确的空格选择器是([\s\t]+)$,它表示至少应该匹配末尾的一个空格(空格或制表符),然后可以替换。不过,我没有资源来使用您的特定代码对其进行测试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-10
        • 1970-01-01
        • 1970-01-01
        • 2021-04-29
        • 1970-01-01
        • 2019-02-14
        • 2016-07-16
        相关资源
        最近更新 更多