XML read file

The four methods of reading files in DOM SAX JDOM DOM4J are introduced through code examples

Write in front:

1. The DOM4J method is more efficient and needs to be mastered

2. DOM SAX is provided by java itself

3. JDOM DOM4J is provided separately, and you need to import the jar package into the project yourself. These two methods are relatively simple compared to the previous two.

xml file

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
	<book id="1">
		<name>我不</name>
		<author>大冰</author>
		<year>2017</year>
		<price>39</price>
	</book>
	<book id="2">
		<name>Fairy Tale</name>
		<author>Andersen</author>
		<year>2000</year>
		<price>77</price>
		<language>English</language>
	</book>
</bookstore>

 Note:

1. <?xml version="1.0" encoding="UTF-8"?> This code is the identification of the xml file, where version is the version encoding is the encoding format

2. <bookstore> root node <book id="1"> child node id is the attribute of child node book

1. DOM

package DOM;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.Node;

/**
 * @author Nut
 * @version on April 3, 2018 at 10:34:24 AM
 */
public class DOMtest {

	public static void test() {

		// Create a DocumentBuilderFactory object
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			// Create a DocumentBuilder object
			DocumentBuilder db = dbf.newDocumentBuilder();
			// Load the xml file into the current project through the parser method of the DocumentBuilder object
			Document doc = db.parse("book.xml");
			// Get the set of all book nodes
			NodeList bookList = doc.getElementsByTagName("book");
			// The length of bookList can be obtained through the getLength() method of nodelist
			System.out.println("Total" + bookList.getLength() + "Book");
			for (int i = 0; i < bookList.getLength(); i++) {
				System.out.println("================The following starts to traverse the first " + (i + 1) + "The content of this book ========= =======");
				// Get a book node through the item(i) method, the index value of nodelist starts from 0
				Node book = bookList.item(i);
				// Get all property sets of the book node
				NamedNodeMap bookAtrr = book.getAttributes();
				System.out.println("Number" + (i + 1) + "Total Books" + bookAtrr.getLength() + "Attributes");
				// Traverse the properties of the book
				for (int j = 0; j < bookAtrr.getLength(); j++) {
					// Get a property of the book node through the item(index) method
					Node attr = bookAtrr.item(j);
					// get property name
					System.out.print("属性名:" + attr.getNodeName());
					// get property value
					System.out.println("--attribute value" + attr.getNodeValue());
				}
				/*
				 * // Prerequisite: It is known that the book node has and can only have 1 id attribute // Cast the book node to type Element
				 * Element attr = (Element) bookList.item(i); //
				 * Get the attribute value through the getAttribute("id") method String attrValue =
				 * attr.getAttribute("id"); System.out.println("The attribute value of the id attribute is " +
				 * attrValue);
				 */

				// Parse the child nodes of the book node
				NodeList childNodes = book.getChildNodes();
				// Traverse childNodes to get the node name and node value of each node
				System.out.println("Number" + (i + 1) + "Total in this book" + childNodes.getLength() + "Number of child nodes");
				for (int k = 0; k < childNodes.getLength(); k++) {
					if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
						// Get the node name of the element type node
						System.out.print("The first " + (k + 1) + "node name: " + childNodes.item(k).getNodeName());
						// Get the node value of the element type node
						System.out.println("--node value is: " + childNodes.item(k).getFirstChild().getNodeValue());
						// System.out.println("--node value is: " + childNodes.item(k).getTextContent());
					}
				}
				System.out.println("======================End of traversal" + (i + 1) + "The content of this book ===== ============");
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace ();
		} catch (SAXException e) {
			e.printStackTrace ();
		} catch (IOException e) {
			e.printStackTrace ();
		}
	}

	public static void main(String[] args) {

		DOMtest.test();
	}

}

2. SAX

package SAX;

/**
 * @author Nut
 * @version April 3, 2018 3:25:19 PM The value read by xml is stored in the book object, so this class is created
 */
public class Book {

	private String id;
	private String name;
	private String author;
	private String year;
	private String language;
	private String price;
	
	

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

	public String getPrice() {
		return price;
	}

	public void setPrice(String price) {
		this.price = price;
	}

}
package SAX;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author Nut
 * @version on April 3, 2018 at 2:50:54 pm
 */
public class SAXParserHandler extends DefaultHandler {

	String value;
	Book book;
	ArrayList<Book> bookList;

	public SAXParserHandler() {
		value = null;
		book = new Book();
		bookList = new ArrayList<Book>();
	}

	/*
	 * used to mark the start of parsing (non-Javadoc)
	 *
	 * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
	 * java.lang.String, java.lang.String, org.xml.sax.Attributes)
	 */
	@Override
	public void startDocument() throws SAXException {

		super.startDocument();
		System.out.println("Parsing started");
	}

	/*
	 * used to mark the end of parsing (non-Javadoc)
	 *
	 * @see org.xml.sax.helpers.DefaultHandler#endDocument()
	 */
	@Override
	public void endDocument() throws SAXException {

		super.endDocument();
		System.out.println("End of parsing");
	}

	/*
	 * Parse xml elements (non-Javadoc)
	 *
	 * @see org.xml.sax.helpers.DefaultHandler#startDocument()
	 */
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

		super.startElement(uri, localName, qName, attributes);
		if (qName.equals("book")) {
			System.out.println("---------A certain book starts----------");
			book = new Book();
			for (int i = 0; i < attributes.getLength(); i++) {
				//System.out.println("The first "+(i+1)+" attribute name: "+attributes.getQName(i)+"---value: "+attributes.getValue(i));
				if(attributes.getQName(i).equals("id")){
					book.setId(attributes.getValue(i));
				}
			}
		} else if (!qName.equals("book") && !qName.equals("bookstore")) {
			System.out.print("This book's" + qName + "is");
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
	 * java.lang.String, java.lang.String)
	 */
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {

		super.endElement(uri, localName, qName);
		if (qName.equals("book")) {
			bookList.add(book);
			book = null;
			System.out.println("------------A book is over------------");
			
		} else if (qName.equals("name")) {
			book.setName(value);
		} else if (qName.equals("author")) {
			book.setAuthor(value);
		} else if (qName.equals("year")) {
			book.setYear(value);
		} else if (qName.equals("price")) {
			book.setPrice(value);
		} else if (qName.equals("language")) {
			book.setLanguage(value);
		}

	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {

		super.characters(ch, start, length);
		value = new String(ch, start, length);
		if (!value.trim().equals("")) {
			System.out.println(value);
		}

	}
}
package SAX;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

/**
 * @author Nut
 * @version on April 3, 2018 at 2:39:08 PM
 */
public class SAXtest {

	public static void test() {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser saxParser = factory.newSAXParser();
			SAXParserHandler handler = new SAXParserHandler();
			saxParser.parse("book.xml", handler);
			System.out.println("-----------------------------------------------------------");
			for (Book book : handler.bookList) {
				System.out.println(book.getId());
				System.out.println(book.getName());
				System.out.println(book.getAuthor());
				System.out.println(book.getPrice());
				System.out.println(book.getYear());
				System.out.println(book.getLanguage());
				System.out.println("222222222222");
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}

	}

	public static void main(String[] args) {

		SAXtest.test();
	}

}

3. JDOM

Note: JDOM needs to import    the official download address of the jar package Jdom-2.0.5.jar here

package JDOM;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

/**
 * @author Nut
 * @version on April 3, 2018 at 4:56:12 PM
 */
public class JDOMtest {

	public static void test() {
		// Perform JDOM parsing of the books.xml file
		// Ready to work
		// 1. Create a SAXBuilder object
		SAXBuilder saxBuilder = new SAXBuilder();
		try {
			// 2. Create an input stream and load the xml file into the input stream
			InputStreamReader in = new InputStreamReader(new FileInputStream("book.xml"), "UTF-8");
			// 3. Load the input stream into saxBuilder through the build method of saxBuilder
			Document doc = saxBuilder.build(in);
			// 4. Get the root node of the xml file through the document object
			Element root = doc.getRootElement ();
			// 5. Get the List collection of child nodes under the root node
			List<Element> bookList = root.getChildren();
			// continue parsing
			for (Element el : bookList) {
				System.out.println("======Start parsing the first" + (bookList.indexOf(el) + 1) + "Book======");
				// Parse the property collection of the book
				List<Attribute> attrList = el.getAttributes();
				for (Attribute attr : attrList) {
					// get property name
					String attrName = attr.getName();
					// get property value
					String attrValue = attr.getValue();
					System.out.println("Attribute name: " + attrName + "----Attribute value: " + attrValue);
				}

				// Traverse the node names and node values ​​of the child nodes of the book node
				List<Element> bookChildren = el.getChildren();
				for (Element child : bookChildren) {
					System.out.println("Node name:" + child.getName() + "----Node value:" + child.getValue());
				}
				System.out.println("======End parsing" + (bookList.indexOf(el) + 1) + "Book======");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace ();
		} catch (FileNotFoundException e) {
			e.printStackTrace ();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
	}

	public static void main(String[] args) {

		JDOMtest.test();
	}

}

4. DOM4J

Note: DOM4J needs to import the jar package   dom4j-1.6.1.jar download URL here

package DOM4J;

import java.io.File;
import java.util.Iterator;
import java.util.List;

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

/**
 * @author Nut
 * @version on April 3, 2018 at 7:45:09 PM
 */
public class DOM4Jtest {

	public static void test() {
		// Parse the books.xml file
		// Create an object reader of SAXReader
		SAXReader reader = new SAXReader();
		try {
			// Load the books.xml file through the read method of the reader object to obtain the docuemnt object.
			Document document = reader.read(new File("book.xml"));
			// Get the root node bookstore through the document object
			Element bookstore = document.getRootElement();
			// Get the iterator through the elementIterator method of the element object
			Iterator<?> iterator = bookstore.elementIterator();
			// Traverse the iterator to get the information in the root node (books)
			while(iterator.hasNext()){
				System.out.println("======Start traversing a book=====");
				Element book = (Element) iterator.next();
				// Get the property name and property value of the book
				List<Attribute> bookAttrs = book.attributes();
				for (Attribute attr : bookAttrs) {
					System.out.println("Attribute name: " + attr.getName() + "--Attribute value: "
							+ attr.getValue());
				}
				Iterator<?> itt = book.elementIterator();
				while (itt.hasNext()) {
					Element bookChild = (Element) itt.next();
					System.out.println("Node name: " + bookChild.getName() + "--Node value: " + bookChild.getStringValue());
				}
				System.out.println("======End of traversing a book=====");
			}
		} catch (DocumentException e) {
			e.printStackTrace ();
		}
	}

	public static void main(String[] args) {

		DOM4Jtest.test();
	}

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325457195&siteId=291194637