2012-09-14 30 views
0

嘗試使用XSLT在我的XML中創建定義列表。定義列表創建

這裏是什麼我輸入看起來像一個例證:

  <p> 

    <i>word1</i> definition text here <br /> 
    <br /> 
       <i>word1</i> definition text here <br /> 
    <br /> 
       <i>word1</i> definition text here <br /> 
    <br /> 
       <i>word1</i> definition text here <br /> 
    <br /> 
       <i>word1</i> definition text here <br /> 

</p> 

的「定義的文字在這裏」在上面的XML是我要標記,包括在我的輸出未標記的文本節點。 一個我想要的輸出的例證是下面:

<dl> 
    <di> 
     <dt>word1</dt> 
     <dd>definition text here<dd> 
    <di> 
<dl> 

我至今模板不工作:

<xsl:template match="p"> 

     <dl> 
      <dt> 
       <xsl:value-of select="./i/node()"/> 
      </dt> 

      <dd> 
       <xsl:sequence select="./text()" /> 
      </dd> 
     </dl> 

    </xsl:template> 

任何人都知道一個快速簡便的方法來做到這一點?

在此先感謝。

回答

1

這種轉變

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="p"> 
    <dl> 
     <di><xsl:apply-templates/></di> 
    </dl> 
</xsl:template> 

<xsl:template match="i"> 
    <dt><xsl:value-of select="."/></dt> 
</xsl:template> 

<xsl:template match="text()[preceding-sibling::*[1][self::i]]"> 
    <dd><xsl:value-of select="normalize-space()"/></dd> 
</xsl:template> 
</xsl:stylesheet> 

時所提供的XML文檔應用(這是嚴重畸形 - 修正這裏):

<p> 
    <i>word1</i> definition text here 
    <br /> 
    <br /> 
    <i>word2</i> definition text here 
    <br /> 
    <br /> 
    <i>word3</i> definition text here 
    <br /> 
    <br /> 
    <i>word4</i> definition text here 
    <br /> 
    <br /> 
    <i>word5</i> definition text here 
    <br /> 
</p> 

產生想要的,正確的結果

<dl> 
    <di> 
     <dt>word1</dt> 
     <dd>definition text here</dd> 
     <dt>word2</dt> 
     <dd>definition text here</dd> 
     <dt>word3</dt> 
     <dd>definition text here</dd> 
     <dt>word4</dt> 
     <dd>definition text here</dd> 
     <dt>word5</dt> 
     <dd>definition text here</dd> 
    </di> 
</dl> 

並顯示在瀏覽器中

字1
定義文本這裏這裏
單詞2
定義文本
WORD3
定義文本這裏
word4
這裏定義的文本
的word5
定義文本這裏
+0

感謝Dimitre的回覆,對於格式錯誤的輸入感到抱歉。這實際上是我的輸入文檔看起來像我正在處理一些非常不好的標記爲我的輸入。 – Laterade

+0

@Laterade,哦,沒關係。我的回答對你有用嗎? –

+0

是的,但是我的文本節點沒有被拾取。它捕獲每個並將其放入

,但由於某種原因,text()的模板不匹配。另外,我現在想
之內的
,有沒有簡單的調整你的代碼,我可以做到這一點? – Laterade

1

您需要在輸入中爲每個i發出一個di元素,而不是輸入中的每個p。首先,將您的代碼移至i的模板。

在您的輸入中,每個i後面緊跟着一個文本節點,其中包含要標記爲dd的文本。這必須嵌入di元素中,所以它需要i在模板中進行處理,這樣的事情(未測試):

<xsl:template match='i'> 
    <di> 
    <dt><xsl:value-of select="."/></dt> 
    <dd><xsl:value-of select="following-sibling::text()[1]"/></dd> 
    </di> 
</xsl:template> 
<xsl:template match="p/text() | p/br"/> 

如果一些定義已經嵌入標記,你需要一個更復雜的方式來填充元素,但足夠的一天是它的邪惡。你問了一些快速簡單的事情。

+0

感謝您的回答,我沒能納入我的樣式表=(這一點。我的輸入與我在我的問題中發佈的內容不同,而且我無法使用輸入文件處理它。感謝您的回覆。 – Laterade

相關問題