Dom 解析XML文件

stu.xml:

<?xml version="1.0"?>
<students>
 <student id='001'>
    <name>zhangsan</name>
    <age>20</age>
 </student>
 <student id='002'>
    <name>李四</name>
    <age>23</age>
    </student>
 <student id="003">
    <name>wangwu</name>
    <age>21</age>
 </student>
 <student id="004">
    <name>zhaoliu</name>
    <age>26</age>
 </student>
 <haha>hello,world</haha>
</students>

Dom操作类:JaxpDemoByDom


package day4;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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 JaxpDemoByDom {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		//1.获取documentBuilder工厂对象 
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		//2.可以通过工厂获取DocumentBuilder对象
		DocumentBuilder builder=factory.newDocumentBuilder();
		//3.使用DocumentBuilder对象的解析方法,与xml文件关联。获取该文件的document对象
		Document document=(Document)builder.parse(new File("stu.xml"));
		System.out.println(document.getDocumentElement().getNodeName());
		getNode(document);
		
		System.out.println("获取节点通过id");
		Element stuElement=(Element)document.getElementsByTagName("student").item(1);
		stuElement.setIdAttribute("id", true);
		getNodeById(document,"002");
		System.out.println("添加一个学生节点");
		addStu(document);
		System.out.println("写操作");
		writeToFile(document);
	}
	
	/*
	 * 将xml的document对象进行本地存储(汉字乱码,不知为什么)
	 */
	
	public static void writeToFile(Document document) throws Exception{
		//1.获取转化者工厂。
		TransformerFactory factory=TransformerFactory.newInstance();
		//2.通过工厂获取转换者对象
		Transformer former=factory.newTransformer();
		//3.使用转换者对象的transform方法。
		//需要传入2个对象。一个Source:DOMSource;一个Result:StreamResult.
		
		//3.1 获取源
		DOMSource source=new DOMSource(document);
		
		//3.2 获取结果
		StreamResult result=new StreamResult(new OutputStreamWriter(new FileOutputStream("newstu.xml"),"gbk"));
		
		former.setOutputProperty(OutputKeys.INDENT, "yes");
		former.setOutputProperty(OutputKeys.METHOD, "xml");
		former.transform(source, result);
	}
	/**
	 * 添加一个学生节点(这个方法有问题)
	 */
	private static void addStu(Document document){
		//1.创建一个节点
		Element stu=document.createElement("student");
		stu.setAttribute("id", "007");
		
		Element name=document.createElement("name");
		name.setTextContent("zzzz");
		Element age=document.createElement("age");
		age.setTextContent("999");
		
		stu.appendChild(name);
		stu.appendChild(age);
		
		Element root=document.getDocumentElement(); 
		root.appendChild(stu);
		
		System.out.println(root.getNodeName());
	}
	
	
	
	
	
	/**
	 * 获取节点通过id.必须要让标签中的属性被setIdAttribute("属性名",true)设置为ID类型。
	 * @param stu
	 */
	private static void getNodeById(Document document,String id){
		Element stu=document.getElementById(id);
		System.out.println(stu.getTagName());
		System.out.println(stu.getElementsByTagName("name").item(0).getTextContent());
	}
	
	private static void printStu2(Element stu){
		String name=stu.getElementsByTagName("name").item(0).getTextContent();
		String age=stu.getElementsByTagName("age").item(0).getTextContent();
		System.out.println(name+":"+age);
	}
  private static void printStu(Element stu) {
		// TODO Auto-generated method stub
		NodeList list=stu.getChildNodes();
		for(int x=0;x<list.getLength();x++){
			Node node=list.item(x);
			if(node.getNodeType()==Node.ELEMENT_NODE){
				Element ele=(Element)node;
				System.out.println(ele.getTagName()+":"+ele.getTextContent());
			}
		}
	}
/**
   * 获取节点
   */

	private static void getNode(Document document) {
		// TODO Auto-generated method stub
		NodeList list=document.getElementsByTagName("student");
		Element element=(Element)list.item(0);
		NodeList list2=element.getChildNodes();
		
		Node node=list2.item(0);
		System.out.println(list2.getLength());
		System.out.println(node.getTextContent()+";;;"+node.getNodeName()+"...."+node.getNodeType()+"..."+node.getNodeValue());
		
		for(int x=0;x<list.getLength();x++){
			Node no=list.item(x);
			
			Element node2=(Element)list.item(x);
			printStu2(node2);
			//System.out.println(no.getNodeName());
			/*if(no.getNodeType()==1){
				System.out.println(no.getNodeName()+":"+no.getTextContent());
			}*/
			//近似等价如下操作
			if(no.getNodeType()==Node.ELEMENT_NODE){
				Element ele=(Element)no;
				printStu(ele);
			}
		}
		/*for(int x=0;x<list.getLength();x++){
			 Element element=(Element)list.item(x);
			 System.out.println(element.getAttribute("id"));
			 //System.out.println(element.getChildNodes().item(0).getNodeName());
			 NodeList list2=element.getChildNodes();
			 for(int a=0;a<list2.getLength();a++){
			      System.out.println(",,,,,"+list2.item(a).getNodeName()+",,,,");
			      System.out.println("-----"+list2.item(a).getNodeValue().trim()+"---");

			 }
		}*/
	}
}


你可能感兴趣的:(xml,exception,String,list,Class,import)