dom操作xml文件,讀取指定的數據

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * dom操作xml文件,讀取指定的數據
 * @author Alexgaoyh
 *
 */
public class DOMTest {

	/* build a DocumentBuilderFactory */
	DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

	public static void main(String[] args) {
		DOMTest parser = new DOMTest();
		Document document = parser.parse("F://books.xml");
		/* get root element */
		Element rootElement = document.getDocumentElement();

		/* get all the nodes whose name is book */
		NodeList nodeList = rootElement.getElementsByTagName("book");
		if (nodeList != null) {
			for (int i = 0; i < nodeList.getLength(); i++) {
				/* get every node */
				Node node = nodeList.item(i);
				/* get the next lever's ChildNodes */
				NodeList nodeList2 = node.getChildNodes();
				for (int j = 0; j < nodeList2.getLength(); j++) {
					Node node2 = nodeList2.item(j);
					if (node2.hasChildNodes()) {
						System.out.println(node2.getNodeName() + ":" + node2.getFirstChild().getNodeValue());
					}
				}
			}
		}
	}

	/* Load and parse XML file into DOM */
	public Document parse(String filePath) {
		Document document = null;
		try {
			/* DOM parser instance */
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			/* parse an XML file into a DOM tree */
			document = builder.parse(new File(filePath));
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return document;
	}
}


/*----------books.xml
  <?xml version="1.0" encoding="UTF-8"?> 
 <books> 
   <book id="01" name="book1"> 
      <title>Harry Potter</title> 
      <author>J K. Rowling</author> 
   </book> 
   <book id="02" name="book2">
      <title>Thinking in Java</title>
      <author>Bruke</author>
   </book> 
 </books> 
 */

發佈了20 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章