在java中排序xml元素 [英] sort the xml elements in java
本文介绍了在java中排序xml元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我需要用java中的姓氏对xml文件中的数据进行排序,这里是xml文件。
So I need to sort the data from the xml file by last name in java, and here is the xml file
<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>
这里是我到目前为止,能够打印代码,但是如何排序他们以姓氏?请帮助
and here is what I have so far, able to print the code out, but how do I sort them by last name? please help
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();
}
}
}
推荐答案
将每个名称添加到类似于 ArrayList
Add each name to something like an ArrayList
ArrayList<String> names = new ArrayList<>(25);
/*...*/
String lastName = information.getElementsByTagName("last").item(0).getTextContent();
String firstName = information.getElementsByTagName("first").item(0).getTextContent();
names.add(lastName + " " + firstName);
/*.../
Collections.sort(names);
您可能会发现收藏教程也有兴趣...
You might find the Collections tutorial of some interest as well...
这篇关于在java中排序xml元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文