Sortieren Sie die xml-Elemente in java

So, ich muss Sortieren Sie die Daten aus der xml-Datei durch den letzten Namen in java, und hier ist die xml-Datei

        <employeeList>
        <employee>
            <name>
                <last>Johnson</last>
                <first>Jason</first>
            </name>
        </employee>
        <employee>
            <name>
                <last>McGrady</last>
                <first>Mike</first>
            </name>
        </employee>
        <employee>
            <name>
                <last>Allen</last>
                <first>Chris</first>
            </name>
        </employee>
        <employee>
            <name>
                <last>Zeller</last>
                <first>Tom</first>
            </name>
        </employee>

        <employee>
            <name>
                <last>Camp</last>
                <first>Alex</first>
            </name>
        </employee>

und hier ist was ich habe, so weit, in der Lage, drucken Sie den code aus, aber wie kann ich die Sortierung nach Nachnamen? bitte helfen Sie

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class SortLastName {
   public static void main(String[] args)
 {    
  try{ 
     File employeesList = new File("employees.xml");
     DocumentBuilderFactory employeesFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder employeesBuilder = employeesFactory.newDocumentBuilder();
    Document employees = employeesBuilder.parse(employeesList);
     employees.getDocumentElement().normalize();
     NodeList nEmployeesList = employees.getElementsByTagName("employee");
     int totalEmployees = nEmployeesList.getLength();

  for (int a = 0; a < totalEmployees; a++)
  {
     Node list = nEmployeesList.item(a);   
     if (list.getNodeType() == Node.ELEMENT_NODE)
     {
        Element information = (Element) list;
        String lastName = information.getElementsByTagName("last").item(0).getTextContent();
        String firstName = information.getElementsByTagName("first").item(0).getTextContent();
        System.out.println("Last name: " + lastName );
        System.out.println("First name: " + firstName);
        System.out.println();
        }
     }
     }
  catch(Exception e)
  {
     e.printStackTrace();
  }

}
}

  • Fügen Sie die Elemente, um so etwas wie eine Liste und Verwendung von Sammlungen.Sortieren
InformationsquelleAutor Qll | 2013-09-11
Schreibe einen Kommentar