DOM用法

package naixi;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Demo2 {

	public static void main(String[] args) {
		Demo2 d = new Demo2();
		try {
			Document document = d.getDocument("src/naixi/dom.xml");	
			//d.testDocument(document);
			//d.show(document);
			d.save(document, "src/naixi/dom1.xml");
			d.add(document, "src/naixi/dom2.xml");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public Document getDocument(String path) throws Exception {
		//获取 获取 稳当对象解析器的工厂类
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		//得到解析器
		DocumentBuilder documentBuilder = factory.newDocumentBuilder();
		//通过解析器获取文档对象模型
		return documentBuilder.parse(path);		
	}
	//解析xml的测试方法1
	/*	public void testDocument(Document document) {
		//获取PhoneInfo
		NodeList childNodes = document.getChildNodes();
//		System.out.println(childNodes.getLength());
		//得到下一个节点
		Node phoneInfo = childNodes.item(0);//获取集合中的元素		
		//获取元素节点的名称
		System.out.println(phoneInfo.getNodeName());
		NodeList nodeList = phoneInfo.getChildNodes();
//		System.out.println(nodeList.getLength());
		//去除文本节点
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node item = nodeList.item(i);
			if(item.getNodeType()==Node.ELEMENT_NODE) {
				//证明是元素节点
				Element ele =(Element)item;
				System.out.println(ele.getAttribute("name"));
				NodeList childNodes2 = ele.getChildNodes();
				for (int j = 0; j 

你可能感兴趣的:(java)