1. 程式人生 > >parse xml document using dom method

parse xml document using dom method

image etl 技術 fire user ges bsp there rate

the bookstore.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<bookname>weicheng</bookname>
<author>qianzhongshu</author>
</book>
<book id="2" value="2_2">
<bookname>yidoudewunv</bookname>
<author>chuangduankangcheng</author>
</book>
<book id="3" class="3_3">
<bookname>a song of ice and fire</bookname>
<author>george martin</author>
</book>
</bookstore>

package com.user;

import java.io.IOException;

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

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Bookstore {

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
// TODO Auto-generated method stub





NodeList nodeList=DocumentBuilderFactory.newInstance().
newDocumentBuilder().parse("src/com/user/Bookstore.xml").getElementsByTagName("book");



System.out.println("There are "+nodeList.getLength()+" books");


for(int i=0;i<nodeList.getLength();i++){

System.out.println("======"+(i+1)+" ");
Node node=nodeList.item(i);
NamedNodeMap nameNodeMap=node.getAttributes();
NodeList childnodeList=node.getChildNodes();


for(int j=0;j<nameNodeMap.getLength();j++){




Node nodeMap=nameNodeMap.item(j);
System.out.println(nodeMap.getNodeName()+": "+nodeMap.getNodeValue());





}

for (int k=0;k<childnodeList.getLength();k++){




Node childNode=childnodeList.item(k);
if (childNode.getNodeType()==Node.ELEMENT_NODE){

System.out.println(childNode.getNodeName()+": "+childNode.getFirstChild().getNodeValue());

}






}




System.out.println(" "+(i+1)+"------");





}




}

}

run the java program:

技術分享

parse xml document using dom method