对xml的读和写

原创
2017/01/13 10:19
阅读数 73

学习了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();

    }

     

   }

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部