java解析xml文件

package com.softeem.xml;

import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class TestDOM {

	/**
	 * @param args
	 */
	
	public void parse(String path){
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(path);
		    Element root=doc.getDocumentElement();
		    System.out.println(root.getNodeName());
		    System.out.println(root.getNodeType());//属性结点
		    System.out.println(root.getNodeValue());
		    Node child = root.getFirstChild();
		    String test="";
		    if(child!=null){
		    	test=child.getNodeValue();
		    	 System.out.println(test);
		    	 System.out.println(child.getNodeName());
		    }
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestDOM td = new TestDOM();
		td.parse("HelloWorld.xml");
	}

}


HelloWord.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<display>denis</display>

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