代码改变世界

Dom解析xml小程序

2012-07-23 10:26  Lves Li  阅读(130)  评论(0编辑  收藏  举报

Dom解析xml

(用Dom解析xml并以原样输出)

package WildCat.Xml.Dom;

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.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class testXml1_3 {

	/**
	 * @param args
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 */
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		//step1.获得工厂
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		//setp2.获得解析器
		DocumentBuilder db=dbf.newDocumentBuilder();
		//step3获得Document对象(根节点)
		Document doc=db.parse(new File("test.xml"));
		//获得根元素节点
		Element root=doc.getDocumentElement();
		
		parseElement(root);
	}
	
	public static void parseElement(Element ele)
	{
		//get the tag'sName
		String tagName=ele.getNodeName();
		//获得所有的孩子
		NodeList children=ele.getChildNodes();
		System.out.print("<"+tagName);
		NamedNodeMap map=ele.getAttributes();
		if (null!=map)
		{
			for (int j=0;j<map.getLength();j++)
			{
				//向下类型转换
				Attr attr=(Attr)map.item(j);
				//获得属性名
				String attrName=attr.getNodeName();
				//获得属性值
				String attrValue=attr.getNodeValue();
				System.out.print(" "+attrName+"=\""+attrValue+"\"");
				
			}
			
		}
		System.out.print(">");
		
		for (int i=0;i<children.getLength();i++)
		{
			Node node=children.item(i);
			//get the node's type
			short nodeType=node.getNodeType();
			if (Node.ELEMENT_NODE==nodeType)
			{
				//go on 递归
				parseElement((Element)node);
			}
			else if (Node.TEXT_NODE==nodeType)
			{
				//if it is text 
				System.out.print(node.getNodeValue());
				
			}
			else if (Node.COMMENT_NODE==nodeType)
			{
				System.out.print("<!--");
				Comment comment=(Comment)node;
				//获得注释的内容
				String data=comment.getData();
				System.out.println(data+"-->");
			}
			
		}
		System.out.print("</"+tagName+">");
		
	
		
	}
	
	

}