对xml的读和写

前端之家收集整理的这篇文章主要介绍了对xml的读和写前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

学习了dom4J操作xml文件,读取xml,生成xml,

读取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

猜你在找的XML相关文章