读取xml
public void get(File in) {
SAXReader reader = new SAXReader();//获取解析器
Document document;
try {
document = reader.read(in);//读取XML文件获取Document对象
Element root = document.getRootElement();////获取根节点元素对象
List<Element> childElements = root.elements();////获取当前节点下的所有节点
for(Element element:childElements){
List<Attribute> attributeList = element.attributes();//获取字节点中的属性
for (Attribute attr : attributeList) {
System.out.println(attr.getName() + ": " + attr.getValue());
}
List<Element> elementList = element.elements();//获取字节点下的所有节点
for (Element ele : elementList) {
System.out.println(ele.getName() + ": " + ele.getText());
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
生成xml
public void xmlWriteDemoByDocument2(){
Document doc=DocumentHelper.createDocument();
Element ele=doc.addElement("students");
ele.addComment("学生信息");
Element ele2=ele.addElement("student");
Element eleName=ele2.addAttribute("id","001");
eleName.addElement("name").setText("小钱");
eleName.addElement("sex").setText("男");
eleName.addElement("age").setText("12");
eleName.addElement("school").setText("次奥学");
XMLWriter xmlWriter;
try {
xmlWriter=new XMLWriter(new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\工作\\02.xml")));
xmlWriter.write(doc);
xmlWriter.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
原文链接:https://www.f2er.com/xml/294499.html