zoukankan      html  css  js  c++  java
  • Dom4j解析、生成Xml

     1
    以下代码未Xml的解析和生成代码

    <?xml version="1.0" encoding="UTF-8"?> 2 <users> 3 <user> 4 <ticket> 5 <username>liyang</username> 6 <password>Aaaa1111</password> 7 <group>C</group> 8 </ticket> 9 </user> 10 11 <user> 12 <ticket> 13 <username>liyang1</username> 14 <password>Aaaa1111</password> 15 <group>C</group> 16 </ticket> 17 </user> 18 19 <user> 20 <ticket> 21 <username>liyang2</username> 22 <password>Aaaa1111</password> 23 <group>C</group> 24 </ticket> 25 </user> 26 </users>

    -------------------------------------------------------------------------------
    dom4j解析xml
     1 public static void parseXml(String url) {
     2         SAXReader read = new SAXReader();
     3         try {
     4             Document doc = read.read(new File(url));
     5             Element rootElement = doc.getRootElement();
     6             Iterator<?> it = rootElement.elementIterator();
     7             while (it.hasNext()) {
     8                 Element element = (Element) it.next();
     9                 Iterator<?> eleIterator = element.elementIterator();
    10                 while (eleIterator.hasNext()) {
    11                     Element el = (Element) eleIterator.next();
    12                     System.out.println("username:" + el.elementText("username") + "---password"
    13                             + el.elementText("password") + "---group:" + el.elementText("group"));
    14                 }
    15             }
    16             System.out.println("rootElement" + rootElement.toString());
    17         } catch (DocumentException e) {
    18             e.printStackTrace();
    19         }
    20     }
    
    

    dom4j生成xml

    public static void generaterXml(File dest) {
            Document doc = DocumentHelper.createDocument();
            Xml.parseXml("D:/properties/user.xml");
            Element rss = doc.addElement("rss");
            rss.addAttribute("version", "2.0");
            Element channel = rss.addElement("channel");
            Element title = channel.addElement("title");
            title.setText("上海移动互联网产业");
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("GBK");
            try {
                XMLWriter writer = new XMLWriter(new FileOutputStream(dest), format);
                writer.setEscapeText(false);
                writer.write(doc);
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        call generaterXml(new File("D:/properties/a.xml"));
     
  • 相关阅读:
    第二阶段冲刺第二天
    第二阶段冲刺第一天
    学习进度表_十四周
    购买图书
    学习进度表_十三周
    寻找水王续
    学习进度表_十二周
    《梦断代码》读后笔记_4
    找水王
    学习进度表_十一周
  • 原文地址:https://www.cnblogs.com/lhl-shubiao/p/dom4j.html
Copyright © 2011-2022 走看看