DOM解析XML文档

利用DOM解析技术,将外部XML文档全部内容解析出来按原格式输出:

 

public static void main(String[] args) throws Exception {
		//获得DOM解析器工厂
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		//获得DOM解析器
		DocumentBuilder db=dbf.newDocumentBuilder();
		//获得DOM对象
		Document document =db.parse(new File("dom.xml"));
		//获得XMl根元素节点
		Element root = document.getDocumentElement();
		
		String charset = document.getXmlEncoding();
		
		System.out.println("<?xml version=\"1.0\" encoding=\""+charset+"\"?>");
		
		parseElement(root);
		
	}
	
	private static void parseElement(Element element){
		
		String tagName=element.getNodeName();
		
		NodeList children = element.getChildNodes();
		
		
		
		System.out.print("<"+tagName);
		
		NamedNodeMap map = element.getAttributes();
		
		if(null!=map){
			
			for(int i=0;i<map.getLength();i++){
				
				Attr attr = (Attr)map.item(i);
			
				String attrName = attr.getName();
				String attrValue = attr.getValue();
				
				System.out.print(" " + attrName + "=\""+attrValue+"\"");
				
			}
		}
		System.out.print(">");
		
		for(int i=0;i<children.getLength();i++){
			
			Node node=children.item(i);
			
			short nodeType = node.getNodeType();
			
			if(nodeType==Node.ELEMENT_NODE){
				
				parseElement((Element)node);
			}
			else if(nodeType == Node.TEXT_NODE){
				
				System.out.print(node.getNodeValue());
			}
			else if(nodeType == Node.COMMENT_NODE){
				
				System.out.print("<!--");
				
				Comment comment = (Comment)node;
				
				String data = comment.getData();
				
				System.out.print(data);
				
				System.out.print("-->");
			}
		}
		System.out.print("</"+tagName+">");
	}
 

你可能感兴趣的:(xml)