Java面试题目之备忘十九

递归解析xml文件里面的所有内容

 

 

package com.test;

import java.io.File;

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

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;

public class DOMTreeTest
{
	public static void main(String[] args) throws Exception
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		DocumentBuilder builder = factory.newDocumentBuilder();
		
		Document document = builder.parse(new File("candidate.xml"));
		
		Element root = document.getDocumentElement();
		
		parseXML(root);
		
	}
	
	public static void parseXML(Element e)
	{
		System.out.print("<" + e.getTagName());
		
		NamedNodeMap map = e.getAttributes();
		
		if(null != map)
		{
			for(int i = 0 ; i < map.getLength() ; ++i)
			{
				Node node = map.item(i);
				
				System.out.print(" " + node.getNodeName() + "=\"" + node.getNodeValue() + "\"");
			}
			
			System.out.print(">");
		}
		
		NodeList list = e.getChildNodes();
		
		for(int i = 0 ;i  < list.getLength() ; ++i)
		{
			Node node = list.item(i);
			
			//表明该节点是一个元素
			if(Element.ELEMENT_NODE == node.getNodeType())
			{
				parseXML((Element)node);
			}
			else
			{
				System.out.print(node.getNodeValue());
			}
		}
		
		System.out.print("</" + e.getNodeName() + ">");
		
	}

}

 

candinate.xml

 

<?xml version="1.0"?>
<PEOPLE hello="world">
	<PERSON PERSONID="E01">
		<NAME>Tony Blair</NAME>
		<ADDRESS>10 Downing Street, London, UK</ADDRESS>
		<TEL>(061) 98765</TEL>
		<FAX>(061) 98765</FAX>
		<EMAIL>[email protected]</EMAIL>
	</PERSON>
	<PERSON PERSONID="E02">
		<NAME>Bill Clinton</NAME>
		<ADDRESS>White House, USA</ADDRESS>
		<TEL>(001) 6400 98765</TEL>
		<FAX>(001) 6400 98765</FAX>
		<EMAIL>[email protected]</EMAIL>
	</PERSON>
	<PERSON PERSONID="E03">
		<NAME>Tom Cruise</NAME>
		<ADDRESS>57 Jumbo Street, New York, USA</ADDRESS>
		<TEL>(001) 4500 67859</TEL>
		<FAX>(001) 4500 67859</FAX>
		<EMAIL>[email protected]</EMAIL>
	</PERSON>
	<PERSON PERSONID="E04">
		<NAME>Linda Goodman</NAME>
		<ADDRESS>78 Crax Lane, London, UK</ADDRESS>
		<TEL>(061) 54 56789</TEL>
		<FAX>(061) 54 56789</FAX>
		<EMAIL>[email protected]</EMAIL>
	</PERSON>
</PEOPLE>
 

 

 

你可能感兴趣的:(java,xml,面试)