DOM解析xml文件
程序员文章站
2022-05-29 08:20:59
...
1.请分别运用dom解析和dom4j解析将文件中student.xml解析出来
提示:1.写一个student的基类
2.运用dom解析步骤将解析出来的内容放到student对象中
*student.xml
public class ZuoYe1 {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse("src/student.xml");
Node rootNode=document.getFirstChild();
NodeList list=rootNode.getChildNodes();
List<Student1> list2=new ArrayList<>();
for(int i=0;i<list.getLength();i++) {
Node node=list.item(i);
if(!"#text".equals(node.getNodeName())) {
Class clazz=Student1.class;
Student1 stu=(Student1) clazz.newInstance();
NodeList list1=node.getChildNodes();
for(int j=0;j<list1.getLength();j++) {
Node node1=list1.item(j);
if(!"#text".equals(node1.getNodeName())) {
//System.out.println(node1.getNodeName()+":"+node1.getTextContent());
String name=node1.getNodeName();
String content=node1.getTextContent();
String name1="set"+name.substring(0,1).toUpperCase()+name.substring(1);
Method method=clazz.getMethod(name1, String.class);
method.invoke(stu, content);
}
}
list2.add(stu);
}
}
System.out.println(list2.size());
for(Student1 stu:list2) {
System.out.println(stu.toString());
}
}
}