【问题标题】:How can one style xml using xslt while keeping the tags in their original order? [closed]如何在使用 xslt 的同时保持标签原始顺序的一种样式 xml? [关闭]
【发布时间】:2012-08-01 15:37:44
【问题描述】:

这就是问题所在。我有一个 xml 文件,其中有多个标签,取决于编写它们的人,最终可能以任何顺序排列。我需要创建一个 xls 文件来设置它的样式,同时保持标签的原始顺序。这是xml:

<content>
<h>this is a header</h>
<p>this is a paragraph</p>
<link>www.google.com</link>
<h> another header!</h>
</content>

【问题讨论】:

  • 您当前的 XSLT 是什么?您在哪里遇到问题?
  • 我发现很难想象您是如何编写代码来重新排序这些元素的,而无需非常努力地这样做。如果您向我们展示您的代码,我们将能够告诉您哪里出错了。
  • 我不想重新排序元素...正如我在帖子中所说的那样。
  • 如果您不展示您的 XSLT,您至少可以向我们展示所需的输出应该是什么吗?

标签: html xml xslt


【解决方案1】:

XSLT 不会自行对元素重新排序,除非您告诉它这样做。如果您正在匹配元素,并用其他元素替换它们,它只会按照我找到它们的顺序处理它们。

如果您只想用 HTML 元素替换元素,您只需为每个元素编写一个匹配的模板,然后在其中输出您需要的 HTML 元素。例如,要将 h 元素替换为 h1 元素,您可以这样做

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

h1 元素将在 h 元素在原始文档中的位置输出。这是完整的 XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" indent="yes"/>

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

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

   <xsl:template match="link">
      <a href="{text()}">
         <xsl:apply-templates select="@*|node()"/>
      </a>
   </xsl:template>

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

当应用于您的示例文档时,输出如下

<body>
   <h1>this is a header</h1>
   <p>this is a paragraph</p>
   <a href="www.google.com">www.google.com</a>
   <h1> another header!</h1>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2016-11-19
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多