XML(DOM SAX JDOM DOM4J)

前端之家收集整理的这篇文章主要介绍了XML(DOM SAX JDOM DOM4J)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

XML()可扩展标记语言,AJAX=(异步)JavaScript+XML

XML更适合数据交互,减轻访问服务器的负担,操作完成之后一次性上传数据,要求环境不高的时候,可以保存数据(使能XML数据库和原生XML数据库


DOM

例子一:DOM解析XML文件

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class DOMDemo1 {
	public static void main(String args[]) throws Exception {
		//取得DocumentBuilderFactory类的对象
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		//取得DocumentBuilder类的对象
		DocumentBuilder builder = factory.newDocumentBuilder();
		//定义Document接口对象,通过DocumentBuilder类进行DOM树的转换操作
		//读取指定路径的XML文件
		Document doc = builder.parse("D:"+File.separator+"XML"+File.separator+"dom_demo1.xml");
		//查找name的节点
		NodeList nodeList = doc.getElementsByTagName("name");
		//输出NodeList中第一个子节点中文本节点的内容
		System.out.println(nodeList.item(0).getFirstChild().getNodeValue());
	}
}
dom_demo1.xml
<?xml version="1.0" encoding="gb2312"?>
<!--<?xml-stylesheet type="text/css" href="style.css"?>-->
<info>
	<name>lql</name>
</info>


例子二:DOM解析XML文件---循环取节点多的数据
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.NodeList;

public class DOMDemo2 {
	public static void main(String args[])throws Exception{
		//取得DocumentBuilderFactory类的对象
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		//取得DocumentBuilder类的对象
		DocumentBuilder builder = factory.newDocumentBuilder();
		//定义Document接口对象,通过DocumentBuilder类进行DOM树的转换操作
		//读取指定路径的XML文件
		Document doc = builder.parse("D:"+File.separator+"XML"+File.separator+"dom_demo2.xml");
		//查找link节点
		NodeList nodeList = doc.getElementsByTagName("link");
		//输出NodeList中第一个子节点中文本节点的内容
		for(int i=0;i<nodeList.getLength();i++){//循环输出节点内容
			Element element = (Element) nodeList.item(i);//取得每一个元素
			System.out.print("姓名:"+element.getElementsByTagName("name").
					item(0).getFirstChild().getNodeValue());
			System.out.println(" email:"+element.getElementsByTagName("email").
					item(0).getFirstChild().getNodeValue());
		}
	}
}
dom_demo2.xml
<?xml version="1.0" encoding="gb2312"?>
<!--<?xml-stylesheet type="text/css" href="style.css"?>-->
<info>
	<link>
		<name>lql</name>
		<email>tony.liu@xxx.com</email>
	</link>
	<link>
		<name>Tony</name>
		<email>lql@xxx.com</email>
	</link>
</info>
例子三:写入XML数据
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;

public class DOMDemo3 {
	public static void main(String agrs[])throws Exception{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.newDocument();//创建一个新的文档
		//建立各个操作节点
		Element info = doc.createElement("info");
		Element link = doc.createElement("link");
		Element name = doc.createElement("name");
		Element email = doc.createElement("email");
		//设置节点的文本内容,即为每一个节点添加文本节点
		name.appendChild(doc.createTextNode("lql"));
		email.appendChild(doc.createTextNode("tony.liu@xxx.com"));
		link.appendChild(name);
		link.appendChild(email);
		info.appendChild(link);
		doc.appendChild(info);//文档上保存节点
		//输出到文档的文件中
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer t = tf.newTransformer();
		t.setOutputProperty(OutputKeys.ENCODING,"GBK");//设置编码
		DOMSource source = new DOMSource(doc);			//输出文档
		//指定输出位置
		StreamResult result = new StreamResult(new File("D:"+
				File.separator+"XML"+File.separator+"dom_demo3.xml"));
		t.transform(source,result);
		
	}
}

SAX

首先编写一个MySAX文件

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class MySAX extends DefaultHandler{	//定义SAX解析器

	public void startDocument(){
		System.out.println("<?xml version=\"1.0\" encoding=\"GBK\"?>");
	}
	
	public void endDocument(){
		System.out.println("\n 文档读取结束...");
	}
	
	public void startElement(String uri,String localName,String qName,Attributes attributes){
		System.out.print("<");
		System.out.print(qName);
		if(attributes != null){
			for(int x= 0 ;x<attributes.getLength();x++){
				System.out.print(" "+attributes.getQName(x)+"=\""
						+attributes.getValue(x)+"\"");
			}
		}
		System.out.print(">");
	} 
	
	public void endElement(String uri,String qName){	//元素结束
		System.out.print("</");
		System.out.print(qName);
		System.out.print(">");
	}
	
	public void characters(char[] ch,int start,int length){//取得元素内容
		System.out.print(new String(ch,start,length));//输出内容
	}
}
调用MySAX
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class TestSAX {
	public static void main(String[] args)throws Exception{
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		parser.parse("D:"+File.separator+"XML"+
				File.separator+"dom_demo2.xml",new MySAX());
	}
}

JDOM
import java.io.File;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class ReadXML {
	public static void main(String[] args)throws Exception {
		SAXBuilder builder = new SAXBuilder();
		Document read_doc = builder.build("D:"+File.separator+"XML"+File.separator+"WriteXML.xml");
		Element stu = read_doc.getRootElement();//读取根元素
		List list = stu.getChildren("link");
		for(int i=0;i<list.size();i++){
			Element e = (Element)list.get(i);
			String name = e.getChildText("name");
			String id = e.getChild("name").getAttribute("id").getValue();
			String email = e.getChildText("email");
			System.out.println(name+" "+email);
		}
	}
}

WriteXML.xml

<?xml version="1.0" encoding="GBK"?>
<info><link><name id="lql">lql</name><email>tony.liu@shheguo.com</email></link></info>
jdom解析需要开源架包

DOM4J

解析数据

import java.io.File;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DOM4JReader {
	public static void main(String[] args) throws Exception{
		File file = new File("D:"+File.separator+
				"XML"+File.separator+"dom_demo2.xml");
		SAXReader reader = new SAXReader();
		Document doc = reader.read(file);//读取xml文件
		//JDOM操作的时候是要取得根节点
		Element element = doc.getRootElement();// 取得根节点
		// 现在应该根据根节点找到全部的子节点,link
		Iterator iter = element.elementIterator();
		while(iter.hasNext()){
			Element elem = (Element) iter.next();
			System.out.print(elem.elementText("name")+" ");
			System.out.println(elem.elementText("email"));
		}
	}
}

dom_demo2.xml

<?xml version="1.0" encoding="gb2312"?>
<!--<?xml-stylesheet type="text/css" href="style.css"?>-->
<info>
	<link>
		<name>lql</name>
		<email>tony.liu@xxx.com</email>
	</link>
	<link>
		<name>Tony</name>
		<email>123@xxx.com</email>
	</link>
</info>


写入数据
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class DOM4JWriter {
	public static void main(String[] args)throws Exception {
		Document doc = DocumentHelper.createDocument();
		Element info = doc.addElement("info");
		Element link = info.addElement("link");
		Element name = link.addElement("name");
		Element email = link.addElement("email");
		Element link1 = info.addElement("link");
		Element name1 = link1.addElement("name");
		name.setText("lql");
		email.setText("tony.liu@shheguo.com");
		name1.setText("tony");
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("GBK");
		XMLWriter writer = new XMLWriter(new FileOutputStream(new File(
				"d:"+File.separator+"XMl"+File.separator+"DOM4JWriter.xml")));
		writer.write(doc);
		writer.close();
	}
}

dom4j解析xml架包 原文链接:https://www.f2er.com/xml/298881.html

猜你在找的XML相关文章