2

我有以下格式的 XML,我想重新格式化:

<blocks>
    <!-- === apples === -->
    <block name="block1">
        ...
    </block>
    <!-- === bananas === -->
    <block name="block2">
        ...
    </block>
    <!-- === oranges === -->
    <block name="block3">
        ...
    </block>
</blocks>

我的问题是我不知道如何选择每个块标签上方的评论。我有以下 XSL:

<xsl:template match="//blocks">
        <xsl:apply-templates select="block" />
</xsl:template>
<xsl:template match="block">
    <xsl:apply-templates select="../comment()[following-sibling::block[@name = ./@name]]" />
    <xsl:value-of select="./@name" />
</xsl:template>
<xsl:template match="comment()[following-sibling::block]">
    <xsl:value-of select="."></xsl:value-of>
</xsl:template>

我正在尝试的输出是:

=== 苹果 ===
block1
=== 香蕉 ===
block2
=== 橙子 ===
block3

但我能得到的最好的是:

=== 苹果 ===
=== 香蕉 ===
=== 橙子 ===
block1
=== 苹果 ===
=== 香蕉 ===
=== 橙子 ===
block2
=== 苹果 == =
=== 香蕉 ===
=== 橙子 ===
block3

如果这有什么不同,我正在使用 PHP。

4

2 回答 2

3

您的样式表有点过于复杂。

您应该尝试下面的样式表,您会发现它与您想要的输出匹配!

<xsl:template match="//blocks">
        <xsl:apply-templates select="block" />
</xsl:template>
<xsl:template match="block">
    <xsl:apply-templates select="preceding-sibling::comment()[1]" />
    <xsl:value-of select="./@name" />
</xsl:template>
<xsl:template match="comment()">
    <xsl:value-of select="."></xsl:value-of>
</xsl:template>

此代码始终匹配在当前块标记之前开始的 1 或 0 条注释。

于 2009-11-06T08:52:53.810 回答
0

您也可以在第一个应用模板而不是第二个应用模板中应用注释模板,以便它按顺序发生 - 此外,此解决方案取决于源 xml 中数据的顺序。

<xsl:template match="//blocks">
        <xsl:apply-templates select="block | comment()" />
</xsl:template>

PS:-您可以避免在表达式中使用“//”,因为它可能不是最佳的。

[编辑]完整的样式表

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="//blocks">
  <xsl:apply-templates select="block | comment()"/>
 </xsl:template>
 <xsl:template match="block">
  <xsl:value-of select="./@name"/>
 </xsl:template>
 <xsl:template match="comment()">
  <xsl:value-of select="."/>
 </xsl:template>
</xsl:stylesheet>

如果需要换行符,请在块和注释中打印值后添加以下语句。

<xsl:text>&#10;</xsl:text>
于 2009-11-06T08:46:55.400 回答