package com.ij34.bean; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.core.io.UrlResource; public class UrlResourceTest { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub UrlResource url=new UrlResource("file:test.txt"); System.out.println(url.getFilename()); System.out.println(url.getURI()); System.out.println(url.getDescription()); System.out.println(url.getClass()); System.out.println(url.getInputStream()); System.out.println(url.getFile()); SAXReader sax=new SAXReader(); Document document=sax.read(url.getFile()); Element el=document.getRootElement(); List list=el.elements(); for(Iterator it=list.iterator();it.hasNext();){ Element test=(Element) it.next(); List l=test.elements(); for(Iterator i=l.iterator();i.hasNext();){ Element e=(Element) i.next(); System.out.println(e.getText()); } } } }
<?xml version="1.0" encoding="UTF-8"?> <books> <book> <name>java入门经典</name> <author>周星驰</author> </book> <book> <name>大数据入门经典</name> <author>李小龙</author> </book> </books>
SerlvetContextResource版本
<%@page import="java.net.URL"%> <%@page import="org.dom4j.Document"%> <%@page import="java.util.Iterator,java.util.List,org.dom4j.Document,org.dom4j.Element,org.dom4j.io.SAXReader"%> <%@page import="org.springframework.web.context.support.ServletContextResource"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% ServletContextResource urls=new ServletContextResource(application,"WEB-INF/test.txt"); out.println(urls.getFilename()+"<br/>"); out.println(urls.getURI()+"<br/>"); out.println(urls.getDescription()+"<br/>"); out.println(urls.getClass()+"<br/>"); out.println(urls.getInputStream()+"<br/>"); out.println(urls.getFile()+"<br/>"); SAXReader sax=new SAXReader(); Document document=sax.read(urls.getFile()); Element el=document.getRootElement(); List list=el.elements(); for(Iterator it=list.iterator();it.hasNext();){ Element test=(Element) it.next(); List l=test.elements(); for(Iterator i=l.iterator();i.hasNext();){ Element e=(Element) i.next(); out.println(e.getText()+"<br/>"); } } %> </body> </html>