使用 XSL 设置 XML 格式

问题描述 投票:0回答:1

我正在使用 java DOM 读取 xml 文件,向其中插入一个新元素(标签),然后将其存储到文件中。我想按其属性之一对其进行排序,在保存文件时使用 XSL。但对于 XSL 我还是个新手。

所以,如果我有这样的 xml :

<movie-theater>
    <catalog>
      <movie title="StarWars" director="George Lucas" madeIn="Holliwood"/>
      <movie title="LordOfTheRings" director="Peter Jackson" madeIn="New Zeland"/>
      <movie title="Batman" director="Tim Burton" madeIn="Holliwood"/>
    <catalog>
</movie-theater>

我想要像这样排序的 xml :

<movie-theater>
    <catalog>
      <movie title="Batman" director="Tim Burton" madeIn="Holliwood"/>
      <movie title="LordOfTheRings" director="Peter Jackson" madeIn="New Zeland"/>
      <movie title="StarWars" director="George Lucas" madeIn="Holliwood"/>
    <catalog>
</movie-theater>

通过应用如下所示的 XSL 模板: (再说一次,我是 xsl 的新手)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/movie-theater/catalog">
        <xsl:for-each select="movie">
            <xsl:sort select="@title"/>
            <xsl:value-of select="."/>              
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

你能帮我解决一下吗?

xml xslt
1个回答
0
投票

我认为这里采取的最佳方法是使用 identity transform 模板作为默认模板,并且仅在通过包含

movie
指令将模板应用于
sort
元素时例外:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="catalog">
    <xsl:apply-templates select="movie">
        <xsl:sort select="@title"/>
    </xsl:apply-templates>
</xsl:template>

</xsl:stylesheet>
© www.soinside.com 2019 - 2024. All rights reserved.