XSLT 将一个特定的 XML 元素放在所有其他元素之前

XSLT to put one particular XML element before all others

需要 XSLT 1.0 解决方案。如果必须的话,我的问题类似于XSLT Change element order and I'll take this answer,但我希望我能做类似'put this_element first, and retain the original order of all the rest of them'的事情。输入是这样的,其中 ... 可以是任何一组简单元素或文本节点,但没有处理指令或注释。另见下文。

<someXML>  
  <recordList>  
    <record priref="1" created="2009-06-04T16:54:35" modification="2014-12-16T14:56:51" selected="False">  
      ...
      <collection_type>3D</collection_type>  
      ...  
      <object_category>headgear</object_category>  
      <object_name>hat</object_name>  
      <object_number>060998</object_number>  
      ...  
    </record>  
    <record priref="3" created="2009-06-04T11:54:35" modification="2020-08-05T18:24:33" selected="False">  
      ...
      <collection_type>3D</collection_type>  
      <description>a very elaborate coat</description>  
      <object_category>clothing</object_category>  
      <object_name>coat</object_name>  
      <object_number>060998</object_number>  
    </record>
  </recordList>
</someXML>

这将是所需的输出。

<someXML>  
  <recordList>  
    <record priref="1" created="2009-06-04T16:54:35" modification="2014-12-16T14:56:51" selected="False">  
      <object_category>clothing</object_category>  
      ...
      <collection_type>3D</collection_type>  
      ...  
      <object_name>hat</object_name>  
      <object_number>060998</object_number>  
      ...  
    </record>  
    <record priref="3" created="2009-06-04T11:54:35" modification="2020-08-05T18:24:33" selected="False">   
      <object_category>clothing</object_category>  
      ...
      <collection_type>3D</collection_type>  
      <description>a very elaborate coat</description>  
      <object_name>coat</object_name>  
      <object_number>060998</object_number>  
    </record>
  </recordList>
</someXML>

如果 object_category 放在第一位,然后在记录中稍后再次出现,即按原始顺序在标签中出现,这可能没问题。

我会添加一些背景知识。这个 API 产生了大约 900.000 XML 条记录,每条记录按字母顺序排列具有不同的标签(元素名称)。大约有 170 个不同的元素名称(这就是为什么我不想单独列出它们的原因,除非没有其他方法)。 XML 被摄取到这个图形数据库中。这需要时间,但如果我们将 object_category 视为记录中的第一个元素,则可以加快速度。

编辑:我们可以配置API,但不能配置API后面的C#代码。我们逐步遍历数据库,逐步摄取约 100 条记录的块。如果我们不指定任何其他内容,我们将得到 XML ,如上例所示。我们还可以指定 XSL sheet 来转换 XML。这就是我们想要在这里做的。

这个例子含糊不清,因为我们不知道所有这些 ... 占位符代表什么。我想这应该适合你:

XSLT 1.0

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

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

<xsl:template match="record">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="object_category"/>
        <xsl:apply-templates select="node()[not(self::object_category)]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>