2015-09-07 65 views
1

我想包裝文本節點並使用XSL使用標籤構建它們。 下面是一個示例。如何使用XSL包裝帶有標籤的XML文本

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<root> 
    <section> 
     <container> 
      aaa 
      <box> 
       book 
      </box> 
      bbb 
      <box> 
       pen 
      </box> 
      ccc 
      <superscript> 
       3 
      </superscript> 
      ddd 
     </container> 
    </section> 
</root> 

是否有可能得到如下結果?

<div> 
    <p>aaa</p> 
    <div>book</div> 
    <p>bbb</p> 
    <div>pen</div> 
    <p>ccc<span>3</span>ddd</p> 
</div> 

我很高興你能再次幫助我!

回答

1

是否有可能得到如下結果?

是。假設你開始了copy idiom,然後你可以添加以下內容:

<xsl:strip-space elements="*"/> 

<!-- these we want to turn into a <div> and then process children --> 
<xsl:template match="box | container | section | formula"> 
    <div> 
     <xsl:apply-templates /> 
    </div> 
</xsl:template> 

<!-- if text node but not directly inside <box> --> 
<xsl:template match="text()[not(parent::box)]"> 
    <p> 
     <xsl:value-of select="." /> 
    </p> 
</xsl:template> 

<!-- any other text node as-is --> 
<xsl:template match="text()"> 
    <xsl:value-of select="." /> 
</xsl:template> 

注1:您的示例XML不是有效的XML,但我相信你的意思</container>,不</formula>

注2:複製成語將複製所有不匹配的東西。如果您不想要,請將其更改爲:

<!-- remove anything we do not need --> 
<xsl:template match="node() | @*"> 
    <xsl:apply-templates /> 
</xsl:template> 

編輯:更正了代碼中的一些缺陷。它現在創建(添加的空間爲了便於閱讀)以下內容:

<div> 
    <div> 
     <p>aaa</p> 
     <div>book</div> 
     <p>bbb</p> 
     <div>pen</div> 
     <p>ccc</p> 
    </div> 
</div> 
+0

總是感謝亞伯。我做到了!。我爲我的錯誤標籤道歉。我想從你那裏得到更多的提示。我重寫我的代碼都XSL和我想要的結果。我在XML中添加了'superscript'標籤和文本'ddd',我怎樣編寫XSL才能得到如下結果:'

ccc ddd

'?可能嗎? – tara

+0

@tara,是的,只需爲'superscript'添加一個匹配的模板,就完成了。這可能是一個好主意[在這裏閱讀模板匹配](http://stackoverflow.com/questions/2138774/understanding-apply-templates-matching)和[這裏(評估順序,然後一些)](HTTP ://stackoverflow.com/questions/1531664/in-what-order-do-templates-in-an-xslt-document-execute-and-do-they-match-on-the),因爲這是[核心的XSLT](http://lenzconsulting.com/how-xslt-works/)。隨意投票和[接受我的回答](http://stackoverflow.com/help/why-vote)如果它幫助你。 – Abel

相關問題