2013-01-04 19 views
3

我有一個轉換XML文檔,定義我們的HTML爲HTML格式的相當簡單的XSL樣式表(請不要問爲什麼,這只是我們必須做的方式...)什麼是更好的XSL樣式創建HTML標籤的方法?

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

<xsl:template match="HtmlElement"> 
    <xsl:element name="{ElementType}"> 
    <xsl:apply-templates select="Attributes"/> 
    <xsl:value-of select="Text"/> 
    <xsl:apply-templates select="HtmlElement"/> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="Attributes"> 
    <xsl:apply-templates select="Attribute"/> 
</xsl:template> 

<xsl:template match="Attribute"> 
    <xsl:attribute name="{Name}"> 
    <xsl:value-of select="Value"/> 
    </xsl:attribute> 
</xsl:template> 

問題出來了,當我跑過HTML需要改造的這一點點:

<p> 
     Send instant ecards this season <br/> and all year with our ecards! 
</p> 

中間的<br/>打破了轉型的邏輯,並給了我唯一的段落塊的前半部分:Send instant ecards this season <br></br>。嘗試進行轉換的XML看起來像:

<HtmlElement> 
    <ElementType>p</ElementType> 
    <Text>Send instant ecards this season </Text> 
    <HtmlElement> 
     <ElementType>br</ElementType> 
    </HtmlElement> 
    <Text> and all year with our ecards!</Text> 
</HtmlElement> 

建議?

回答

1

您可以簡單地添加新的規則文本元素,然後同時匹配HTML元素和文本:

<xsl:template match="HtmlElement"> 
    <xsl:element name="{ElementName}"> 
    <xsl:apply-templates select="Attributes"/> 
    <xsl:apply-templates select="HtmlElement|Text"/> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="Text"> 
    <xsl:value-of select="." /> 
</xsl:template> 
+0

現在這將如何影響一個' ...'標籤?我不確定我是否理解你要回答的問題 – CallMeTroggy

+0

@CallMeTroggy嗯,首先,這個XSL根據你在問題中指定的XML輸入生成你想要的HTML輸出。所以這應該是一些東西;)只要它們遵循你在問題中提出的XML結構,它也可以很好地適用於任何嵌套的HTML元素 - 只需試一試! – phihag

+0

啊哈!是的,這正是我所需要的。我對XSL還比較陌生,但我並沒有真正看到/理解管道的作用(仍然有點不確定,但是現在有了更好的把握)。謝謝@phihag! – CallMeTroggy

0

你可以使樣式有點更通用的爲了通過調整模板HtmlElement來處理額外的元素以確保它首先應用模板來Attributes元素,然後對所有元素除了AttributesHtmlElement元件通過在xsl:apply-templates的選擇屬性使用謂詞濾波器。

內置模板將匹配Text元素,並將text()複製到輸出。

另外,可以刪除當前已聲明的根節點的模板(即match="/")。它只是重新定義已經由內置模板規則處理的內容,並且沒有做任何改變行爲的東西,只是混亂了你的樣式表。

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

<!-- <xsl:template match="/"> 
     <xsl:apply-templates/> 
    </xsl:template>--> 

    <xsl:template match="HtmlElement"> 
     <xsl:element name="{ElementType}"> 
      <xsl:apply-templates select="Attributes"/> 
      <!--apply templates to all elements except for ElementType and Attributes--> 
      <xsl:apply-templates select="*[not(self::Attributes|self::ElementType)]"/> 
     </xsl:element> 
    </xsl:template> 

    <xsl:template match="Attributes"> 
     <xsl:apply-templates select="Attribute"/> 
    </xsl:template> 

    <xsl:template match="Attribute"> 
     <xsl:attribute name="{Name}"> 
      <xsl:value-of select="Value"/> 
     </xsl:attribute> 
    </xsl:template> 

</xsl:stylesheet> 
相關問題