java解析xml文档

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.parsers.*;

import org.apache.log4j.Logger;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class MayUtil {

   
    public static Document loadXML(URL url) {
	DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
	DocumentBuilder builder;
	Document doc=null;
	try {
	    builder = factory.newDocumentBuilder();
	    try {
		
		

		 doc=builder.parse(new InputSource(new InputStreamReader(url.openStream(),"UTF-8")));
		} catch (SAXException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		} catch (IOException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
	    
	} catch (ParserConfigurationException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return doc;
    }
      public static Document loadXML(File file) {
	DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
	DocumentBuilder builder;
	Document doc=null;
	try {
	    builder = factory.newDocumentBuilder();
	    try {
		    doc=builder.parse(file);
		} catch (SAXException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		} catch (IOException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
	    
	} catch (ParserConfigurationException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return doc;
    }
    public static void main(String[] args){
	System.out.println("start");
	Document doc=loadXML(new File("d:/ins.xml"));
	
	NodeList elementA=doc.getElementsByTagName("row");
	for(int i=0;i<elementA.getLength();i++){
	    Node child=elementA.item(i);
	    if(child instanceof Element){
		NamedNodeMap nnmap=child.getAttributes();
		for(int j=0;j<nnmap.getLength();j++){
		    Node node=nnmap.item(j);
		    System.out.println(node.getNodeName());
		    
		}
	    }
	    
	}
	
    }
 
    
    


}

你可能感兴趣的:(java,apache,xml,log4j,J#)