Read xml file content through Java

 

You need to download jar package dom4j: https://dom4j.github.io/

com.zyb.xml Package; 

Import java.io.File; 
Import the java.util.Iterator; 

Import org.dom4j.Attribute; 
Import org.dom4j.Document; 
Import org.dom4j.DocumentException; 
Import org.dom4j.Element; 
Import org.dom4j.io.SAXReader; 

public class testXml { 

	public static void main (String [] args) throws Exception { 
		// the TODO Auto-Generated Method Stub 
		. SAXReader // Create an object for reading. 1 xml file 
		SAXReader reader = new SAXReader (); 
		// read xml file 2, obtained document object. 
		document DOC = reader.Read (new new file ( "the src / book.xml")); 
		.. 3 // Get the root element 
		element root = doc.getRootElement ( ); 
		// get all four subelements in the root element (through the iterator).  
		the iterator <the element> root.elementIterator IT = ();
		the while (it.hasNext ()) {
			
			Element e = it.next();
			//获取id属性(attribute是属性的意思)
			Attribute id = e.attribute("id");
			System.out.println(id.getName()+" = "+id.getStringValue());
			Element author = e.element("author");
			Element money = e.element("price");
			Element time = e.element("time");
			System.out.println(author.getName()+" = "+author.getStringValue());
			System.out.println(money.getName()+" = "+money.getData());
			System.out.println(time.getName()+" = "+time.getText());
			System.out.println("---------------------------------------------------------------");
		}
	}

}

 

operation result:

 

 

  

Guess you like

Origin www.cnblogs.com/cstdio1/p/11627726.html