按属性排序XML文件(Sorting XML file by attribute)

编程入门 行业动态 更新时间:2024-10-27 15:17:57
属性排序XML文件(Sorting XML file by attribute)

我有以下XML代码:

<Group> <GElement code="x"> <Group> <GElement code="x"> <fname>a</fname> <lname>b</lname> </GElement> <GElement code ="f"> <fname>fa</fname> </GElement> </Group> </GElement> <GElement code ="f"> </GElement> </Group>

我希望输出按“代码”排序,如:

<Group> <GElement code ="f"> </GElement> <GElement code="x"> <Group> <GElement code ="f"> <fname>fa</fname> </GElement> <GElement code="x"> <fname>a</fname> <lname>b</lname> </GElement> </Group> </GElement> </Group>

树的深度可以是无穷无尽的,即GElement可以有另一个组等等。

有任何想法吗?

I have a following XML code:

<Group> <GElement code="x"> <Group> <GElement code="x"> <fname>a</fname> <lname>b</lname> </GElement> <GElement code ="f"> <fname>fa</fname> </GElement> </Group> </GElement> <GElement code ="f"> </GElement> </Group>

I would like to have the output sorted by "code" like:

<Group> <GElement code ="f"> </GElement> <GElement code="x"> <Group> <GElement code ="f"> <fname>fa</fname> </GElement> <GElement code="x"> <fname>a</fname> <lname>b</lname> </GElement> </Group> </GElement> </Group>

The depth of the tree can be endless i.e. the GElement can have another Group and so on.

Any ideas?

最满意答案

使用XslCompiledTransform ( 请参阅MSDN )将此styleshet应用于XML文档:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <!-- the identity template copies everything verbatim --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*" /> </xsl:copy> </xsl:template> <!-- special template for <Group> that sorts its children --> <xsl:template match="Group"> <xsl:copy> <xsl:copy-of select="@*" /> <!-- copy attributes, if any --> <xsl:apply-templates select="GElement"> <xsl:sort select="@code" /> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>

XML树的嵌套深度可以是任意的。

Use XslCompiledTransform (see MSDN) to apply this styleshet to your XML document:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <!-- the identity template copies everything verbatim --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*" /> </xsl:copy> </xsl:template> <!-- special template for <Group> that sorts its children --> <xsl:template match="Group"> <xsl:copy> <xsl:copy-of select="@*" /> <!-- copy attributes, if any --> <xsl:apply-templates select="GElement"> <xsl:sort select="@code" /> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>

XML tree nesting depth can be arbitrary.

更多推荐

本文发布于:2023-08-03 01:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382521.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   文件   XML   attribute   Sorting

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!