XSLT转换到自定义XML

问题描述:

对于自定义应用程序,我需要改造的XHTML(自定义)的XML。经过一番实验后,我决定试试php5的XSLT功能,但到目前为止,我无法将嵌套的p标签转换为它们的xml等价物。XSLT转换到自定义XML

Basicly我们有这样的代码:

<p>Some text</p> 
<ol> 
    <li><p>Some more text</p></li> 
    .. 
</ol> 

这需要转化为:

<par>Some text</par> 
<list> 
    <li><par>Some more text</par></li> 
    .. 
</list> 

真正的问题是:我需要包括行内标签,XSL:value-of的是没有选择,而是我使用xsl:copy-of。到目前为止,我有OL模板| UL和P,结果是这样的:

<par>Some text</par> 
<list> 
    <li><p>Some more text</p></li> 
    .. 
</list> 

任何人一些提示,如何实现我真正想要的只是用更复杂的XSLT?

,你建议你可以使用嵌套<xsl:element>标签输出联标签。

喜欢的东西:

<xsl:element name="li"> 
    <xsl:element name="p"> 
    some text 
    </xsl:element> 
</xsl:element> 
+0

你能或许举个例子?我需要把一个模板,这里面,是导致静态或动态(如可我再利用“任意内容和嵌入式标签或者这仅仅输出一组固定的元素和内容)? – 2010-01-29 21:50:27

在这里你去...

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 
    <xsl:output method="xml" indent="yes"/> 
    <!-- ============================================== --> 
    <xsl:template match="/"> 
     <xsl:apply-templates/> 
    </xsl:template> 
    <!-- ============================================== --> 
    <xsl:template match="p"> 
     <xsl:element name="par"> 
      <xsl:apply-templates/> 
     </xsl:element> 
    </xsl:template> 
    <!-- ============================================== --> 
    <xsl:template match="ol"> 
     <xsl:element name="list"> 
      <xsl:apply-templates/> 
     </xsl:element> 
    </xsl:template> 
    <!-- ============================================== --> 
    <xsl:template match="li"> 
     <xsl:element name="li"> 
      <xsl:apply-templates/> 
     </xsl:element> 
    </xsl:template> 
    <!-- ============================================== --> 
</xsl:stylesheet> 
+0

非常感谢!这确实让我更进一步,但似乎内联元素是这样丢失的? – 2010-01-29 22:02:54

+0

你不能拥有它。如果您要求复印,则不会进行进一步的处理。你应该做的是创建一个默认模板来复制元素的名称,并继续处理,并覆盖你正在改变的元素。 – 2010-01-29 22:04:41

+0

“内联元素”是什么意思? – dacracot 2010-01-29 22:05:19

如果你开始与identity transform,用于变换一个名称的元素到另一个元素的一般模式是这样的:值得注意的

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

两件事情:

  1. 通常,除非你肯定知道你变换所述元素没有属性(或者主动打算剥离的属性),则应该使用所示的select属性;不要只用<xsl:apply-templates/>。属性不是子节点,因此应用没有select属性的模板不会将模板应用于它们。

  2. 除非你真的很喜欢打字,几乎从来没有一个理由使用<xsl:element>。例外情况是当您以编程方式生成输出元素的名称时。

其中,实际上,你可以,如果你想获得的所有花式shmancy做:

<xsl:template match="*"> 
    <xsl:variable name="new_name"> 
     <xsl:when test="name()='p'>par</xsl:when> 
     <xsl:when test="name()='ol'>list</xsl:when> 
     <xsl:when test="name()='li'>item</xsl:when> 
     <xsl:otherwise><xsl:value-of select="name()"/></xsl:otherwise> 
    </xsl:variable> 
    <xsl:element name="{$new_name}"> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:element> 
</xsl:template> 
+0

+1(如果可以,还有+1) - 注意'test =“name()='p''不会除非* XSL文档在工作*与XHTML输入相同的默认名称空间。可以用'local-name()'来代替,但用前缀声明XHMTL命名空间并改为'test =“name()='xhtml:p''是更清晰的解决方案。 – Tomalak 2010-02-01 11:04:15