复制代码代码如下:
Paket com.test;
java.io.File importieren;
import java.util.ArrayList;
java.util.List importieren;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
öffentliche Klasse DomXML {
public static void main(String[] args) {
versuchen {
Datei file = new File("e:/People.xml");
DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = Factory.newDocumentBuilder();
Dokument document = builder.parse(file);
Element element = document.getDocumentElement();
List<People> peopleList = new ArrayList<People>();
NodeList peopleNodes = element.getElementsByTagName("People");
for(int i=0;i<peopleNodes.getLength();i++){
Leute Leute = neue Leute();
Element peopleElement = (Element) 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) Instanz des Elements){
Element childPeopleElement = (Element) childPeopleNodes.item(j);
if(childPeopleElement.getNodeType()==Node.ELEMENT_NODE){
if(childPeopleElement.getNodeName().equals("Name")){
people.setEnglishName(childPeopleElement.getAttribute("en"));
people.setName(childPeopleElement.getTextContent());
}
sonst if(childPeopleElement.getNodeName().equals("Alter")){
people.setAge(childPeopleElement.getTextContent());
}
}
}
}
peopleList.add(people);
}
for(Leute Leute: peopleList){
System.out.println(people.getId()+"/t"+people.getName()+"/t"+people.getEnglishName()+"/t"+people.getAge());
}
} Catch (Ausnahme e) {
// TODO 自动生成的 Catch 块
e.printStackTrace();
}
}
}