JavaでXMLファイルを読む方法 – (DOM Parser)
このチュートリアルでは、
DOM XML parser
を使用してXMLファイルを読み込む方法を説明します。 DOMパーサはXMLドキュメント全体を解析し、メモリにロードします。簡単なトラバーサルや操作のために “TREE”構造でモデル化します。
要するに、XMLファイルをhttp://www.w3schools.com/dom/default.asp[DOM]またはツリー構造に変換するので、必要なものを得るためにノードごとにノードをトラバースする必要があります。
1. DOM XMLパーサーの例
この例では、ノードを「名前」で取得し、その値を表示する方法を示します。
/Users/mkyong/staff.xml
<?xml version="1.0"?> <company> <staff id="1001"> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> <staff id="2001"> <firstname>low</firstname> <lastname>yin fong</lastname> <nickname>fong fong</nickname> <salary>200000</salary> </staff> </company>
ReadXMLFile.java
package com.mkyong.seo; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class ReadXMLFile { public static void main(String argv[]) { try { File fXmlFile = new File("/Users/mkyong/staff.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); //optional, but recommended //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("staff"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT__NODE) { Element eElement = (Element) nNode; System.out.println("Staff id : " + eElement.getAttribute("id")); System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent()); System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent()); System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent()); System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } } }
結果
Root element :company ---------------------------- 現在の要素:staffスタッフID:1001名:yong姓:mook kimニックネーム:mkyong給与:100000 現在の要素:staff スタッフID:2001 ファーストネーム:低い 姓:yin fong ニックネーム:fong fong 給与:200000
2.ノードのループ
この例では、同じ “` staff.xml` “を読み込み、ループする方法を示しています
ノードを1つずつ作成し、ノード名と値を出力します。
もしあれば属性。
ReadXMLFile2.java
パッケージcom.mkyong.seo; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory;インポートorg.w3c.dom.Document;インポートorg.w3c.dom.NamedNodeMap; import org.w3c.dom.Node;インポートorg.w3c.dom.NodeList; パブリッククラスReadXMLFile2 { public static void main(String[]args){ 試して{ ファイルファイル=新しいファイル( "/Users/mkyong/staff.xml"); DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); ドキュメントdoc = dBuilder.parse(ファイル); System.out.println( "ルート要素:" doc.getDocumentElement()。getNodeName()); if(doc.hasChildNodes()){ printNote(doc.getChildNodes()); } } catch(例外e){System.out.println(e.getMessage()); } } プライベート静的void printNote(NodeList nodeList){ for(int count = 0; count <nodeList.getLength(); count ++){ ノードtempNode = nodeList.item(count); //make sure it's element node. if(tempNode.getNodeType()== Node.ELEMENT__NODE){ //get node name and value System.out.println("\nNode Name =" + tempNode.getNodeName() + "[OPEN]"); System.out.println("Node Value =" + tempNode.getTextContent()); if(tempNode.hasAttributes()){ //get attributes names and values NamedNodeMap nodeMap = tempNode.getAttributes(); for(int i = 0; i <nodeMap.getLength(); i ++){ ノードノード= nodeMap.item(i); System.out.println( "attr name:" + node.getNodeName()); System.out.println( "attr値:" + node.getNodeValue()); } } if(tempNode.hasChildNodes()){ //loop again if has child nodes printNote(tempNode.getChildNodes()); } System.out.println( "ノード名=" tempNode.getNodeName() "[CLOSE]"); } } } }
結果:
ルート要素:会社 ノード名=会社[OPEN]ノード値=ヨンムクキムムギョン100000低インフォンフォンフォン200000 ノード名= staff[OPEN]ノード値= yong mook kim mkyong 100000 attr name:id attr値:1001 ノード名= firstname[OPEN]ノード値= yongノード名=ファーストネーム[CLOSE] ノード名=ラストネーム[OPEN]ノード値= mook kimノード名=ラストネーム[CLOSE] ノード名=ニックネーム[OPEN]ノード値= mkyongノード名=ニックネーム[CLOSE] ノード名= salary[OPEN]ノード値= 100000ノード名= salary[CLOSE]ノード名= staff[CLOSE] ノード名= staff[OPEN]ノード値=低yin fong fong fong 200000 attr名:id attr値:2001 ノード名=ファーストネーム[OPEN]ノード値=ローノード名=ファーストネーム[CLOSE] ノード名= lastname[OPEN]ノード値= yin fongノード名=姓[CLOSE] ノード名=ニックネーム[OPEN]ノード値= fong fongノード名=ニックネーム[CLOSE] ノード名= salary[OPEN]ノード値= 200000 ノード名=給与[CLOSE]ノード名= staff[CLOSE]ノード名=会社[CLOSE].... ** 注意** あなたはこれに興味があります リンク://java/how-to-get-alexa-in-java/[Alexaランキングを取得する方法 Javaで]。これは、DOMを使用してAlexa XMLの結果を解析する方法を示しています。 ===参考文献 。 http://docs.oracle.com/javase/tutorial/jaxp/dom/when.html[ご利用にあたって DOM]。 http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work[正規化 javaを使ったDOM解析 - どのように動作するのですか?]。 http://www.w3schools.com/dom/default.asp[XML DOMの学習]。 http://www.w3schools.com/dom/dom__nodes.asp[ノードとは何ですか]。 http://www.w3schools.com/dom/dom__element.asp[要素は何ですか?] link://tag/dom/[dom]link://タグ/java/[java]link://タグ/xml/[xml]