XML解析——Java-DOM

5164 ワード

参考になりましたhttp://java.chinaitlab.com/XMLBeans/36082.html
あるコードを参考にしましたが、原文が見つかりませんでした。ご了承ください。
解析対象のxml例:

<?xml version="1.0" encoding="gb2312"?>
<books>
<book email="[email protected]">
    <name>Bible
</name>
    <price>60.0</price>
  </book>
  
  
    <book email="[email protected]">
    <name>TAOCP</name>
    <price>600.0
    </price>
  </book>
</books>
Javaコード:

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

public class TestDom {
	public static void main(String[] args) {
		//test2();
		getSpecTagVal("book.xml", "name");
	}
	/**
	 * getSpecTagVal      tag  ,       
	 * */
	public static void getSpecTagVal(String filename, String tag){
		//String filename = "book.xml";
		//     XML      
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			//   XML    DOM      ,    DOM
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(new File(filename));
			//      
			Element element = document.getDocumentElement();
			//            
			NodeList books = element.getChildNodes();
			for(int i = 0; i < books.getLength(); i++){
				walkNode(books.item(i), tag);
			}
		} catch (Exception ie) {
			ie.printStackTrace();
		}
	}
	public static void test2(){
		String filename = "book.xml";
		//     XML      
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			//   XML    DOM      ,    DOM
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(new File(filename));
			//      
			Element element = document.getDocumentElement();
			//            
			NodeList books = element.getChildNodes();
			if(books != null){
				for(int i = 0; i < books.getLength(); i++){
					Node book = books.item(i);
					System.out.println("==========" + i + "============");
					//System.out.println(book.getAttributes().toString());
					if(book.getNodeType() == Node.ELEMENT_NODE){
						String email = book.getAttributes().getNamedItem("email").getNodeValue();
						System.out.println(email);
						for(Node n = book.getFirstChild(); n != null; n = n.getNextSibling()){
							if(n.getNodeType() == Node.ELEMENT_NODE){
								if(n.getNodeName().equals("name")){
									String name = n.getNodeValue();
									String name1 = n.getFirstChild().getNodeValue();
									System.out.println(name + "
" + name1); } if(n.getNodeName().equals("price")){ //String price = n.getNodeValue(); String price1 = n.getFirstChild().getNodeValue(); System.out.println(price1); } } } } } } } catch (Exception ie) { ie.printStackTrace(); } } public static void test() { String filename = "book.xml"; // XML DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // XML DOM , DOM DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File(filename)); // Element element = document.getDocumentElement(); // NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); walkNode(node); } } catch (Exception ie) { ie.printStackTrace(); } } private static void walkNode(Node anode, String tag) { if(anode.getNodeType() == Node.ELEMENT_NODE && anode.getNodeName() == tag){ System.out.println(anode.getNodeName() + "\t" + anode.getFirstChild().getNodeValue()); } if(anode.hasChildNodes()){ NodeList child = anode.getChildNodes(); for (int i = 0; i < child.getLength(); i++) { walkNode(child.item(i), tag); } } } private static void walkNode(Node anode) { if(anode.getNodeType() == Node.ELEMENT_NODE){ System.out.println(anode.getNodeName() + "\t" + anode.getFirstChild().getNodeValue()); } if(anode.hasChildNodes()){ NodeList child = anode.getChildNodes(); for (int i = 0; i < child.getLength(); i++) { walkNode(child.item(i)); } } }
  このコードは走ることができます。ネット上の多くのコード(私が見たもの)には訳のわからない出力がありますので、自分で修正したコードを貼り付けます。主に初心者の勉強に便利です。コードコメントは多く書かれていません。JDKのAPIを見て、各方法の役割を理解しましょう。
今はxmlの解析についても触れたばかりで、よく分かりません。交流と批判を歓迎します。