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"));