Dom解析
//载入builder工场
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("src/student.xml");
NodeList nodeList=doc.getElementsByTagName("student");
//强类型转换,将node转换为元素
Element element=(Element) nodeList.item(0);
System.out.println("姓名:"+element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
JDOM解析
1. 生成xml
Element student=new Element("student");//定义一个元素
Attribute id=new Attribute("id","1");
Attribute aa=new Attribute("aa","abcd");//定义两个属性
student.setAttribute(id);
student.setAttribute(aa);//将属性赋值给元素
Element name=new Element("name");
name.setText("张三");//给元素设置文本值
Element sex=new Element("sex");
sex.setText("男");
Element age=new Element("age");
age.setText("21");
student.addContent(name);//将元素添加到元素中作为子元素
student.addContent(sex);
student.addContent(age);
Document document=new Document(student);//定义一个文档
XMLOutputter out=new XMLOutputter();//定义一个输出
out.setFormat(out.getFormat().setEncoding("UTF-8"));//设置输出的格式
out.output(document,new FileOutputStream("src/student2.xml"));//输出
2. 访问xml
3. SAXBuilder builder =new SAXBuilder();
Document document=builder.build("src/students.xml");
Element students=document.getRootElement();
List<Element> studentList=students.getChildren("student");
for(int i=0;i<studentList.size();i++){
Element student=studentList.get(i);
String id=student.getChild("name").getAttributeValue("id");
String name=student.getChildText("name");
String sex=student.getChildText("sex");
String age=student.getChildText("age");
System.out.println("学号:"+id+"姓名:"+name+"性别:"+sex+"年龄:" +age);
DOM4J
1. 创建xml
Document document= DocumentHelper.createDocument();
Element student= document.addElement("student");
student.addAttribute("id","1");
student.addAttribute("aa","123");
Element name=student.addElement("name");
Element sex=student.addElement("sex");
Element age=student.addElement("age");
name.setText("张三");
sex.setText("男");
age.setText("21");
OutputFormat out=OutputFormat.createPrettyPrint();
out.setEncoding("UTF-8");
XMLWriter writer=new XMLWriter(new FileOutputStream("src/student3.xml"),out);
writer.write(document);
writer.close();
2. 访问xml
SAXReader saxReader=new SAXReader();
Document document=saxReader.read("src/students.xml");
Element students=document.getRootElement();
Iterator iterator=students.elementIterator();
while(iterator.hasNext()){
Element student=(Element) iterator.next();
Element name=student.element("name");
Element sex=student.element("sex");
Element age=student.element("age");
Attribute id= name.attribute("id");
System.out.println("姓名:"+name.getText());
System.out.println("学号:"+id.getText());
System.out.println("性别:"+sex.getText());
System.out.println("年龄:"+age.getText());
System.out.println("===========");
}
Dom4J解析xml基本步骤
最新推荐文章于 2022-04-20 11:25:48 发布