天天看點

org.w3c.dom解析xml

xml 檔案格式如下:

<?xml version="1.0" encoding="UTF-8"?>  
<category>
	<categoryId>  
	    <oldCategoryId>950347</oldCategoryId>  
	    <newCategoryId>959440,959461,959432,959447</newCategoryId>  
	</categoryId> 
	
	<categoryId>  
	    <oldCategoryId>950351</oldCategoryId>  
	    <newCategoryId>9546,9599,9599</newCategoryId>  
	</categoryId> 

</category>	      

解決程式如下:

package com.newheight.util;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class W3CTest {


	public static void main(String[] args) throws Exception {
		String xmlFile = "file.xml";
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		DocumentBuilder db = dbf.newDocumentBuilder();

		Document domTree = db.parse(xmlFile);
		
		Element  root = domTree.getDocumentElement();
		
		showInfo(root.getNodeName());
		
		NodeList nodes = root.getElementsByTagName("categoryId");
		
		for (int i = 0; i < nodes.getLength(); i++) {
			Element categoryElement = (Element)nodes.item(i);
			NodeList childNodes = categoryElement.getChildNodes();
			for (int j = 0; j < childNodes.getLength(); j++) {
				Node node = childNodes.item(j);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Element childNode = (Element)node;
					showInfo(childNode.getNodeName());
					showInfo(childNode.getFirstChild().getNodeValue());
				}
			}
			
		}
	}

	public static  void showInfo(Object info) {
		System.out.println(info);
	}
}