按字母顺序对 XML 标签进行排序 [英] sort XML tags into alphabetical order

查看:49
本文介绍了按字母顺序对 XML 标签进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道我可以将 XML 文件加载到其中并对其进行排序然后保存文件的方法吗?

anyone know of a way that I can load an XML file into and sort it and then save the file?

我有一个包含一堆设置的 xml 文件..现在越来越难以管理,因为它们没有任何自然的排序顺序......

I have a xml file with a bunch of settings.. and now it is getting hard to manage because they are not in any natural sort order...

例如

<edit_screen_a>
<settings_font_size>
<edit_screen_b>
<display_screen>
<settings_font_name>

排序到:

<display_screen>
<edit_screen_a>
<edit_screen_b>
<settings_font_name>
<settings_font_size>

推荐答案

您可以使用 XSLT 并从命令行运行它.(我推荐 Saxon,但 Xalan 没问题.)

You could use XSLT and run it from the command line. (I'd recommend Saxon, but Xalan would be ok.)

这是一个例子...

XML 输入

<doc>
  <edit_screen_a/>
  <settings_font_size/>
  <edit_screen_b/>
  <display_screen/>
  <settings_font_name/>
</doc>

XSLT 1.0

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

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

  <xsl:template match="doc">
    <doc>
      <xsl:apply-templates>
        <xsl:sort select="name()"/>
      </xsl:apply-templates>      
    </doc>
  </xsl:template>

</xsl:stylesheet>

XML 输出

<doc>
   <display_screen/>
   <edit_screen_a/>
   <edit_screen_b/>
   <settings_font_name/>
   <settings_font_size/>
</doc>

这篇关于按字母顺序对 XML 标签进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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