2015-06-19 89 views
-2

我想用XSLT转换XML结构。使用XSLT转换XML结构

<detaileddescription> 
    <para>Some text</para> 
    <para> 
    <bold>Title</bold> 
    </para> 
    <para>Intro text: 
    <itemizedlist> 
    <listitem> 
     <para>Text</para> 
    </listitem> 
    <listitem> 
     <para>Text</para> 
    </listitem> 
    </itemizedlist> 
    </para> 
</detaileddescription> 

这就是我想要的:

<detaileddescription> 
    <para>Some text</para> 
    <List> 
    <Title>Title</Title> 
    <Intro> 
     Intro text: 
    </Intro 
    <ListItem> 
     <para>Text</para> 
    </ListItem> 
    <ListItem> 
     <para>Text</para> 
    </ListItem> 
    </List> 
</detaileddescription> 

所以在我自己的话说: 如果有<para><bold>,检查<para>以下同胞也是<para>和有一个孩子<para>Text</para>比我想要重建的结构如图所示。

我不确定是否有可能,因为我刚开始使用xslt/xpath。任何人都可以给我一点帮助吗?

+0

这个问题实在太广泛而无法有效回答。花一点时间阅读XSLT模板,以及'following-sibling ::'和'descendant ::'轴。也许你可以更具体地针对你遇到的问题重新制定它。 –

+0

好吧,你是对的。也许我的问题有点不确定。 起初我想为此找到一个测试: “元素A的第一个后续兄弟元素是一个具有子元素B的元素A”。 –

+1

'following-sibling :: * [1] [self :: A [B]]'检查后面的第一个兄弟元素是否是至少有一个'B'元素子元素的'A'元素。请注意,在你的示例中,内部'para'不是外部'para'的孩子,它只是一个后代。 –

回答

1

如果你想使用节点条件的话,我会建议把它们放进匹配模式:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

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

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

    <xsl:template match="detaileddescription/para[bold][following-sibling::*[1][self::para[.//para]]]"> 
     <List> 
      <Title> 
       <xsl:value-of select="bold"/> 
      </Title> 
      <xsl:apply-templates select="following-sibling::*[1]" mode="intro-list"/> 
     </List> 
    </xsl:template> 

    <xsl:template match="detaileddescription/para[.//para][preceding-sibling::*[1][self::para[bold]]]"/> 

    <xsl:template match="detaileddescription/para/text()[1]" mode="intro-list"> 
     <Intro> 
      <xsl:value-of select="."/> 
     </Intro> 
    </xsl:template> 

    <xsl:template match="listitem" mode="intro-list"> 
     <ListItem> 
      <xsl:apply-templates/> 
     </ListItem> 
    </xsl:template> 
</xsl:transform> 

的样本见http://xsltransform.net/3NzcBtK/2

+0

非常感谢。这对我很有帮助。 –