2015-09-01 9 views
2

У меня есть XML, как следует,XSLT - добавить новый узел, анализируя текстовый узел

<doc> 
    <chap> 
     The bowler delivers the ball 
     to the batsman who attempts to 
     hit the ball with his bat away from 
     the fielders so he can run to the 
     other end of the pitch and score a run. 
    </chap> 
</doc> 

Мое требование добавлять новые узлы с именем <p> в <chap> текстовый узел, где добавить <p> узел в каждой новой строке.

Таким образом, требуемый выход,

<doc> 
    <chap> 
     <p>The bowler delivers the ball</p> 
     <p>to the batsman who attempts to</p> 
     <p>hit the ball with his bat away from</p> 
     <p>the fielders so he can run to the</p> 
     <p>other end of the pitch and score a run.</p> 
    </chap> 
</doc> 

Можете ли вы дать мне предложение, как я могу сделать это в XSLT, используя регулярные выражения и отделить текст от перевода строки (#xA).

Я попытался выполнить эту задачу, но не мог придумать, как это сделать.

ответ

2

Вы можете использовать xsl:analyze-string, чтобы выбрать текст между пробелами и символами новой строки:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="2.0"> 
    <xsl:output indent="yes"/> 

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

    <xsl:template match="chap/text()"> 
     <xsl:analyze-string select="." regex="\s*(.*)\n"> 
      <xsl:matching-substring> 
       <p><xsl:sequence select="regex-group(1)"/></p> 
      </xsl:matching-substring> 
     </xsl:analyze-string> 
    </xsl:template> 

</xsl:stylesheet> 

Или вы могли бы использовать tokenize() разделить на переводы строк

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="2.0"> 
    <xsl:output indent="yes"/> 

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

    <xsl:template match="chap/text()"> 
     <xsl:for-each select="tokenize(., '\n')[normalize-space()]"> 
      <p><xsl:sequence select="normalize-space()"/></p> 
     </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 
+0

Спасибо за решение. Это прекрасно работает. +1 – sanjay

Смежные вопросы