-2
<page>
  <p>
    Republic of India (Bhārat Gaṇarājya),[c] is a country in South Asia.
    <br/>It is the seventh-largest country by geographical area.
    <br/> the second-most populous country with over 1.2 billion people, and the most populous democracy in the world.
  </p>
</page>

我需要<br><p>元素替换。

<p>Republic of India (Bhārat Gaṇarājya),[c] is a country in South Asia.</p>
    <p>It is the seventh-largest country by geographical area.</p>
    <p>the second-most populous country with over 1.2 billion people, and the most populous democracy in the world.</p>

这个怎么做 ?

4

1 回答 1

2

一种方法是使用键匹配 p 元素的所有子元素,按最前面的br元素(如果没有前面的br元素,则按父p元素)对它们进行分组。

 <xsl:key 
    name="bits" 
    match="p/node()[not(self::br)]" 
   use="generate-id((..|preceding-sibling::br[1])[last()])"/>

然后,可以匹配p内的所有br元素,并输出 key 内的以下非 br 元素

<p>
    <xsl:copy-of select="key('bits', generate-id())"/>
<p>

对于第一批没有前面br元素的子元素,您也会遇到这种情况。

这是完整的 xslt

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" indent="yes"/>
   <xsl:key name="bits" match="p/node()[not(self::br)]" use="generate-id((..|preceding-sibling::br[1])[last()])"/>

   <xsl:template match="p">
      <p>
         <xsl:apply-templates select="key('bits', generate-id())"/>
      </p>
      <xsl:apply-templates select="br"/>
   </xsl:template>

   <xsl:template match="p/br">
      <p>
         <xsl:apply-templates select="key('bits', generate-id())"/>
      </p>
   </xsl:template>

   <xsl:template match="page">
      <xsl:apply-templates select="@*|node()"/>
   </xsl:template>

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

应用于您的示例 XML 时,将输出以下内容

<p>       
   Republic of India (Bhārat Gaṇarājya),[c] is a country in South Asia.       
</p>
<p>
   It is the seventh-largest country by geographical area.       
</p>
<p>
   the second-most populous country with over 1.2 billion people, and the most populous democracy in the world.       
</p>

这也应该处理嵌套的p元素,以及在文本中保留除p和** 之外的其他 HTML。

于 2012-05-07T09:06:36.350 回答