使用 XSL 对属性进行排序 [英] Using XSL to sort attributes

查看:32
本文介绍了使用 XSL 对属性进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过按名称(而不是值)对每个元素的属性进行排序来规范一些 XML 数据的表示.这个想法是在添加或删除属性时保持文本差异最小,并防止不同的编辑器引入等效的变体.这些 XML 文件受源代码控制,开发人员希望在不求助于专门的 XML 工具的情况下区分更改.

I'm trying to canonicalize the representation of some XML data by sorting each element's attributes by name (not value). The idea is to keep textual differences minimal when attributes are added or removed and to prevent different editors from introducing equivalent variants. These XML files are under source control and developers are wanting to diff the changes without resorting to specialized XML tools.

我很惊讶没有找到有关如何执行此操作的 XSL 示例.基本上我只想要具有排序属性的身份转换.我想出了以下似乎适用于我所有测试用例的方法:

I was surprised to not find an XSL example of how to this. Basically I want just the identity transform with sorted attributes. I came up with the following with seems to work in all my test cases:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
  <xsl:template match="*|/|text()|comment()|processing-instruction()">
    <xsl:copy>
    <xsl:for-each select="@*">
        <xsl:sort select="name(.)"/>
        <xsl:copy/>
      </xsl:for-each>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

作为一个完整的 XSL n00b,我很感激任何关于风格或效率的评论.我认为把它贴在这里可能会有所帮助,因为它似乎至少不是一个常见的例子.

As a total XSL n00b I would appreciate any comments on style or efficiency. I thought it might be helpful to post it here since it seems to be at least not a common example.

推荐答案

由于 xslt 作为一种函数式语言,执行 for-each 对我们人类来说通常是最简单的方法,但对于 XSLT 处理器来说并不是最有效的方法,因为它们无法完全优化电话.

With xslt being a functional language doing a for-each might often be the easiest path for us humans but not the most efficient for XSLT processors since they cannot fully optimize the call.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
  <xsl:template match="*">
    <xsl:copy>
      <xsl:apply-templates select="@*">
        <xsl:sort select="name()"/>
      </xsl:apply-templates>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="@*|comment()|processing-instruction()">
    <xsl:copy />     
  </xsl:template>
</xsl:stylesheet>

在这方面这完全是微不足道的,作为XSL n00b",我认为你确实很好地解决了这个问题.

This is totally trivial in this regards though and as a "XSL n00b" i think you solved the problem very well indeed.

这篇关于使用 XSL 对属性进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆