按字母顺序对 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>