XML and the .NET Framework
xml sorting problem
Question:
I have a xml document and I want to sort the elements with xslt. I want to sort the elements by a give order instead of the aphabetic order.
for example, i have road types, motorway, aroad and broad, in the xml document. I want to sort the elements in motorway, aroad and broad order instead of the aphabetic order which puts aroad and broad in front of motorway.
any idea?
thank you very much.
Answer1:
Please post a minimal but complete XML sample and the result you want to achieve.
MVP XML
Answer2:
Hi,
can you post your XML tree structure please and note the specific areas you need to sort.
Answer3:
<EventList>
<Event>
<RoadName>A1</RoadName>
<Message>A1 closed</Messsage>
<RoadType>aroad</RoadType>
</Event>
<Event>
<RoadName>M1</RoadName>
<RoadType>motorway</RoadType>
</Event>
</EventList>
I want to sort this xml by the RoadType so I can have M1 before A1
<EventList>
<Event>
<RoadName>M1</RoadName>
<Message>Road clear</Messsage>
<RoadType>motorway</RoadType>
</Event>
<Event>
<RoadName>A1</RoadName>
<RoadType>aroad</RoadType>
</Event>
</EventList>
any idea?
Thanks
Answer4:
Here is an XSLT 2.0 stylesheet that you can run with Saxon (http://saxon.sourceforge.net/) or Gestalt (http://gestalt.sourceforge.net/) or AltovaXML (http://www.altova.com/altovaxml.html):
Code SnippetAnswer5:
Here is an XSLT 1.0 solution:
Code SnippetAnswer6:
Thanks for the reply. I am not good at xslt. Can you tell me what "@* | node()" means and what "<xsl:apply-templates select="@*"/>" is for
Thanks
Answer7:
@* as an XPath expression selects all attributes, as an XSLT match pattern it matches any attribute. node() as an XPath expression selects all child nodes, as a match pattern it matches any node (other than attribute nodes and the root node). The xsl: apply-templates select="@*" is in there just in case the EventList element in the real XML has any attributes that need to be copied.
MVP XML
Answer8:
I tried both 1.0 and 2.0 samples you gave.
every time i put <xsl
aram name="road-types" select="('motorway', 'aroad', 'broad')" as="xs
tring*"/> or
<data
ata>...</data
ata> into my stylesheet, the transformation failed.
any idea?
Answer9:
Please mark up code samples as "Code Block" as otherwise they are defaced with emoticons and very hard to read.
As for the stylesheet, the XSLT 2.0 stylesheet works with the processsors I mentioned.
The XSLT 1.0 stylesheet should work with any XSLT 1.0 processor.
If you say the "transformation failed", what exactly happens? Do you get an error when trying to run the transformation? Which XSLT processor exactly do you use? Have you tried the stylesheet as posted or did you make any changes? If you made changes then please show us your current stylesheet.
MVP XML
Related posts
Powered by BlogEngine.NET 1.2.0.0
Sponsor