Example of loading xml resources with classpathresource in spring


This article illustrates how spring uses classpathresource to load XML resources. The details are as follows:

One code

package lee;
import org.springframework.core.io.ClassPathResource;
import org.dom4j.*;
import org.dom4j.io.*;
import java.util.*;
import java.util.*;
public class ClassPathResourceTest
  public static void main(String[] args)
    throws Exception
    //Create a resource object and read the resource from the class loading path
    ClassPathResource cr = new ClassPathResource("book.xml");
    //Get simple information about the resource
    //Creating DOM 4J parser based on Sax
    SAXReader reader = new SAXReader();
    Document doc = reader.read(cr.getFile());
    //Get root element
    Element el = doc.getRootElement();
    List l = el.elements();
    //Traverses all child elements of the root element
    for (Iterator it = l.iterator();it.hasNext() ; )
      //Each node is a Book node
      Element book = (Element)it.next();
      List ll = book.elements();
      //Traverse all the child nodes of the < book > node
      for (Iterator it2 = ll.iterator();it2.hasNext() ; )
        Element eee = (Element)it2.next();

2. Resource documents

<?xml version="1.0" encoding="GBK"?>
Computer book list
   The book
      < book title > crazy Java handout < / book title >
      < author > Li Gang < / author >
   < / book >
   The book
      < book title > lightweight Java EE enterprise application practice < / book title >
      < author > Li Gang < / author >
   < / book >
< / computer book list >

III. operation results

class path resource [book.xml]
Crazy Java handout
Li Gang
Lightweight Java EE enterprise application
Li Gang

More about Java related content, interested readers can see our special topics: “spring framework introduction and advanced tutorial”, “Java data structure and algorithm tutorial”, “Java operation DOM node skills summary”, “java file and directory operation skills summary” and “Java cache operation skills summary”

I hope this article will be helpful to you in Java programming.

Recommended Today

Ubuntu deployment record

For Ubuntu 16.04 Apt get source switching System settings ->Software and updates ->Download from ->Select Chinese ->mirrors.aliyun.com/ubuntu Selecting a domestic source and then updating the language library and other update operations will be faster! Convert to Chinese and add Chinese input method System settings ->Language support ->[the new system will prompt that the language support […]