基于XSLT 1.0实现XML节点排序:将A、B节点前置的技术问询
Solution for Reordering XML Nodes in XSLT 1.0 (BizTalk Compatible)
I get it—working with XSLT 1.0 in an older BizTalk environment can feel restrictive, but we can absolutely achieve your goal of moving all <Message> nodes containing <A> or <B> to the front, while keeping the <Order> and <Article> related messages in their original sequence.
Here's a straightforward XSLT 1.0 stylesheet that does exactly what you need:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <!-- Identity template: copies all nodes/attributes by default --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- Custom template to reorder the Message nodes inside Messages --> <xsl:template match="Messages"> <xsl:copy> <!-- Apply templates to all Message nodes, sorted by priority --> <xsl:apply-templates select="Message"> <!-- Sort rule: prioritize A/B messages first --> <xsl:sort select="number(local-name(*) = 'A' or local-name(*) = 'B')" data-type="number" order="descending"/> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>
How this works:
- Identity Template: This handles copying all existing XML content (nodes, attributes, text) exactly as-is, so we only need to override the behavior for the
<Messages>node where we need reordering. - Sort Logic:
local-name(*) = 'A' or local-name(*) = 'B'checks if the child node of a<Message>is either<A>or<B>. This returns a boolean (trueorfalse).- The
number()function converts that boolean to1(for true) or0(for false). - Using
order="descending"ensures that all messages with a sort value of1(A/B) come before those with0(Order/Article). - Crucially, XSLT 1.0 preserves the original document order for nodes that have the same sort key. So your A/B messages stay in the order they appeared in the input, and the Order/Article messages also retain their original sequence—perfect for your requirement.
Testing this with your sample input will produce exactly the output you provided, with all A/B messages grouped at the start, followed by the original sequence of Order/Article messages.
内容的提问来源于stack exchange,提问作者JohanB
相关产品推荐
相关产品推荐

