复制代码代码如下:
paket com.test;
impor java.io.File;
impor java.util.ArrayList;
impor java.util.List;
import javax.xml.parsers.DocumentBuilder;
impor javax.xml.parsers.DocumentBuilderFactory;
impor org.w3c.dom.Dokumen;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
kelas publik DomXML {
public static void main(String[] args) {
mencoba {
File file = File baru("e:/People.xml");
Pabrik DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
Pembuat DocumentBuilder = pabrik.newDocumentBuilder();
Dokumen dokumen = pembangun.parse(file);
Elemen elemen = document.getDocumentElement();
Daftar<Orang> PeopleList = Daftar Array baru<Orang>();
NodeList peopleNodes = elemen.getElementsByTagName("Orang");
for(int i=0;i<peopleNodes.getLength();i++){
Orang orang = Orang baru();
Elemen peopleElement = (Elemen) peopleNodes.item(i);
people.setId(peopleElement.getAttribute("id"));
NodeList childPeopleNodes = peopleElement.getChildNodes();
for(int j=0;j<childPeopleNodes.getLength();j++){
//DOM解析时候注意子节点前面的空格也会被解析
if(childPeopleNodes.item(j) instanceof Elemen){
Elemen childPeopleElement = (Elemen) childPeopleNodes.item(j);
if(childPeopleElement.getNodeType()==Node.ELEMENT_NODE){
if(childPeopleElement.getNodeName().equals("Nama")){
people.setEnglishName(childPeopleElement.getAttribute("en"));
people.setName(childPeopleElement.getTextContent());
}
else if(childPeopleElement.getNodeName().equals("Umur")){
people.setAge(childPeopleElement.getTextContent());
}
}
}
}
peopleList.tambahkan(orang);
}
for(Orang orang : orangDaftar){
System.out.println(people.getId()+"/t"+people.getName()+"/t"+people.getEnglishName()+"/t"+people.getAge());
}
} tangkapan (Pengecualian e) {
// TODO 自动生成的 menangkap 块
e.printStackTrace();
}
}
}