标签:
XML文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <bookstore> 3 <book id="1"> 4 <name>冰与火之歌</name> 5 <author>乔治马丁</author> 6 <year>2014</year> 7 <price>89</price> 8 </book> 9 <book id="2"> 10 <name>安徒生童话</name> 11 <year>2004</year> 12 <price>77</price> 13 <language>English</language> 14 </book> 15 </bookstore>
Book实体类
1 public class Book { 2 private String id; 3 private String name; 4 private String author; 5 private String year; 6 private String price; 7 private String language; 8 9 // get set 方法生成即可 10 11 }
DOM4J解析XMl文件
1 public class DOM4JTest { 2 private static ArrayList<Book> bookList = new ArrayList<Book>(); 3 4 /** 5 * @param args 6 */ 7 public static void main(String[] args) { 8 // 解析books.xml文件 9 // 创建SAXReader的对象reader 10 SAXReader reader = new SAXReader(); 11 try { 12 // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。 13 Document document = reader.read(new File("src/res/books.xml")); 14 // 通过document对象获取根节点bookstore 15 Element bookStore = document.getRootElement(); 16 // 通过element对象的elementIterator方法获取迭代器 17 Iterator it = bookStore.elementIterator(); 18 // 遍历迭代器,获取根节点中的信息(书籍) 19 while (it.hasNext()) { 20 System.out.println("=====开始遍历某一本书====="); 21 Element book = (Element) it.next(); 22 // 获取book的属性名以及 属性值 23 List<Attribute> bookAttrs = book.attributes(); 24 for (Attribute attr : bookAttrs) { 25 System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); 26 } 27 Iterator itt = book.elementIterator(); 28 while (itt.hasNext()) { 29 Element bookChild = (Element) itt.next(); 30 System.out.println("节点名:" + bookChild.getName() + "--节点值:" + bookChild.getStringValue()); 31 } 32 System.out.println("=====结束遍历某一本书====="); 33 } 34 } catch (DocumentException e) { 35 // TODO Auto-generated catch block 36 e.printStackTrace(); 37 } 38 } 39 }
DOM4J读取XMl
public class DOM4JTest { private void createXML() { // 1.创建document对象,代表整个xml文档 Document document = DocumentHelper.createDocument(); // 2.创建根节点rss Element rss = document.addElement("rss"); // 3.向rss节点中添加version属性 rss.addAttribute("version", "2.0"); // 4.生成子节点及节点内容 Element channel = rss.addElement("channel"); Element title = channel.addElement("title"); Element content = title.addElement("content"); content.setText("本周中期北方明显偏暖 多地气温较同期偏高8℃以上"); // title.setText("<![CDATA[上海移动互联网产业促进中心正式揭牌 ]]>"); // 5.设置生成xml的格式 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); // 6.生成xml文件 File file = new File("rssnews.xml"); XMLWriter writer; try { writer = new XMLWriter(new FileOutputStream(file), format); // 设置是否转义,默认值是true,代表转义 writer.setEscapeText(false); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { new DOM4JTest().createXML(); } }
标签:
原文地址:http://www.cnblogs.com/andy86869/p/5330594.html