2013-01-04 21 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> 
相关问题