3

我有以下要解析以创建 HTML 的 XML 文件。我的问题是我无法按照我的意愿解析它。

我想要做的是将我的输出<items>为 html。所以我希望 a<paragraph>成为 a <div><image>成为 an <img>并且它的子节点成为它的属性 'src' 和 'alt'。

<itemlist>
    <item>
        <paragraph>pA</paragraph>
        <image>
            <url>http://www.com/image.jpg</url>
            <title>default image</title>
        </image>
        <paragraph>pB</paragraph>
        <paragraph>pC</paragraph>
        <link target='#'>linkA</link>
        <paragraph>pD</paragraph>
        <link target='#' >linkB</link>
        <image>
            <url>http://www.com/image2.jpg</url>
            <title>default image 2</title>
        </image>
        </item>
        <item>      
        <paragraph>pB</paragraph>
        <paragraph>pC</paragraph>
        <image>
            <url>http://www.com/image2.jpg</url>
            <title>default image 2</title>
        </image>
        <link target='#'>linkA</link>
        <paragraph>pD</paragraph>
        <link target='#'>linkB</link>
        </item>
    </itemlist>

如果我 <item>通过应用模板执行 foreach 循环并写入值,例如 match='paragraph' 后跟 match='image',那么所有内容都<paragraph>将写在 之前<image>,这不会导致正确的输出。

下面是我期待的输出。有人知道怎么做吗?

<div id="item">
    <div>pA</div>
    <img src='http://www.com/image.jpg' title='default image' />
    <div>pB</div>
    <div>pC</div>
    <a href='#'>linkA</a>
    <div>pD</div>
    <img src='http://www.com/image2.jpg' title='default image 2' />
</div>
<div id="item">
    <div>pB</div>
    <div>pC</div>
    <img src='http://www.com/image2.jpg' title='default image 2' />
    <a href='#'>linkA</a>
    <div>pD</div>
    <a href='#'>linkB</a>
</div>

-----编辑----目前我有这样的东西

    <xsl:for-each select="itemlist/item">
<xsl:apply-templates select="paragraph"/>
<xsl:apply-templates select="link"/>


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

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


</xsl:for-each>
4

1 回答 1

2

这是你想要的 ?:

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

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

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

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

</xsl:stylesheet>
于 2013-01-07T20:14:27.507 回答