简体   繁体   中英

how to sort XML file using java

I have an xml file and want to sort like this in txt file

Soccer | England | Premier League | Blackpool FC - Birmingham City 5-1

 <?xml version="1.0" encoding="UTF-8"?> <LivescoreData> <Sport SportId="1"> <Name language="en">Soccer</Name> <Name language="se">Fotboll</Name> <Category CategoryId="34"> <Name language="en">Australia</Name> <Name language="se">Australien</Name> <Tournament TournamentId="144"> <Name language="en">Hyundai A-League</Name> <Name language="se">Hyundai A-League</Name> <Match MatchId="4616735"> .... etc 

Use dom4j .It's a great library for working with xml files.
You can download it from here .

    SAXReader reader = new SAXReader();
    Document doc = reader.read(new File("myXML.xml"));
    Element content = doc.getRootElement();
    List<Element> myNeededElements = content.elements("neededElementName");

After this you'll have all elements with the name you want (say "neededElementName") in myNeededElements list.

If you have flexible options in selecting a library/framework, one of the solutions is to use XStream and deserialize the xml into a collection of java objects and sort 'em.

For Ex:

List<Employee> employeeList = xStream.fromXML(xmlFile);
Collections.sort(employeeList, new Comparator() { .... });

EDIT : Also check the below links:

1) How to sort XML elements in Java?

2) XSLT Sort

Sorting an XML file can generally be done in a few lines of XSLT or XQuery, and invoking XSLT or XQuery only takes a few lines of Java. However, it's totally unclear from your post what your desired input and output are (or at any rate, what relationship they have to each other.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM