㈠SAX解析器
sax解析适用于对大批的XML进行查询数据,因为它的这种解析不会开辟大量的内存空间所以比较节省资源,另外如果对要解析的XML
文档的节点结构不是很了解,这样便可以通过sax解析。
看下面这段代码:
//*****导包,这些包都是在不同的包下,有点难记*****
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import java.io.IOException;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.FactoryConfigurationError;
import org.xml.sax.Attributes;
//继承至DefaultHandler类,此类定义解析XML的规则,我们要重写5个方法,当解析XML的时候他会自动地被调用。
class MySaxParser1 extends DefaultHandler {
//开始解析文档的时候会被调用,只被调用一次,一般这个方法没有意义
public void startDocument() throws SAXException {
System.out.println("解析xml 文档开始: /n");
}
//当开始解析到某个元素的时候此方法会被调用
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
System.out.println("前缀uri:"+uri);
System.out.println("前缀名:"+localName);
for(int i=0;i<attributes.getLength();i++){
System.out.println("节点属性名称:" + attributes.getQName(i));
System.out.println("节点属性值:"+attributes.getValue(i));
}
System.out.println(qName + " 元素解析开始");
}
//当解析到具体的数据的时候此方法会被调用
public void characters(char[] ch, int start, int length) throws SAXException {
String strObj = new String(ch, start, length);
if (!strObj.startsWith("/n")) {
System.out.println(" 值: " + strObj);
}
}
//当解析某个元素结束的时候此方法会被调用
public void endElement(String url, String localName, String qName) throws SAXException {
System.out.println(qName + "元素解析结束/n");
}
//结束解析文档的时候会被调用,只被调用一次,一般这个方法没有意义
public void endDocument() throws SAXException {
System.out.println("解析xml文档结束/n");
}
}
//测试类
public class Test{
public static void main(String[] args)
{
String uri ="c://a//Example 3.xml"; //*****XML文件的路径*****
try {
SAXParserFactory parserFactory = SAXParserFactory.newInstance(); //★★通过SAXParserFactory类的单态模式创建本类对象
MySaxParser1 mySaxParser1Instance = new MySaxParser1(); //★★创建解析XML的规则类的对象
SAXParser parser = parserFactory.newSAXParser(); //★★通过工厂类创建SAXParser解析对象
parser.parse(uri, mySaxParser1Instance); //★★开始解析,参数是XML的路径还有解析XML规则类对象
} catch (IOException exception) {
exception.printStackTrace();
} catch (SAXException exception) {
exception.printStackTrace();
} catch (ParserConfigurationException exception) {
exception.printStackTrace();
} catch (FactoryConfigurationError exception) {
exception.printStackTrace();
}
}
}
㈡DOM解析器
如果对要解析的XML文档的节点结构很了解,这样便可以通过DOM解析,DOM解析的时候,首先会在内存中通过XML构建一个树状结构,
如果这个XML文件比较大,这样是很费内存的。
看下面这段代码:
== NewBook.xml ==
<?xml version = "1.0"?>
<library>
<book>
<booktitle>京华烟云</booktitle>
<author>林语堂</author>
<price>99.00</price>
</book>
<book>
<booktitle>老人与海</booktitle>
<author>海明威</author>
<price>50.00</price>
</book>
<book>
<booktitle>罗密欧与朱丽叶</booktitle>
<author>莎士比亚</author>
<price>80.00</price>
</book>
</library>
== Book.java (实体Bean) ==
public class Book {
//****对应XML文件中的节点****
private String bookTitle;
private String author;
private String price;
public Book() {
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle ;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
}
== ParseDomDocument.java ==
//第一步,导包
import java.io.IOException;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import java.io.FileWriter;
public class ParseDomDocument {
public ParseDomDocument() {
}
//*****此方法解析XML,并且将数据封装成book对象,放入集合中。*****
public static ArrayList getBookArrayList(String uri) {
ArrayList list = new ArrayList();//创建集合,转载从XML文件中解析的数据
try {
DocumentBuilderFactory DBfactory = DocumentBuilderFactory.newInstance();//★★创建DocumentBuilderFactory的单态模式对象
DocumentBuilder DBbuilder = DBfactory.newDocumentBuilder();//★★通过工厂创建DocumentBuilder对象
Document doc = DBbuilder.parse(uri);//★★通过DocumentBuilder对象解析XML文件,参数是XML的路径,通过此方法,便在内存中加载了整个XML树结构
NodeList nodeList = doc.getElementsByTagName("book");//★★这里是对所有的book节点从内存中解析出来,返回值是NodeList集合对象
for (int i = 0; i < nodeList.getLength(); i++) {
String booktitle = doc.getElementsByTagName("booktitle").item(i).
getFirstChild().getNodeValue(); //★★通过循环,把所有的booktitle子节点从内存中解析出来,getNodeValue()方法可以取出节点中的数据
String author = doc.getElementsByTagName("author").item(i).
getFirstChild().booktitle;
String price = doc.getElementsByTagName("price").item(i).
getFirstChild().getNodeValue();
Book book = new Book();
book.setBookTitle(booktitle);
book.setAuthor(author);
book.setPrice(price);
list.add(book);
}
doc.getElementsByTagName("booktitle").item(0).
getFirstChild().setNodeValue("newValue"); //★★这里是对第一个booktitle节点重新赋值为newValue
//注意,这里修改的是内存中的节点树的值,原有的实际中的XML文件中的值并没有被修改
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
//下面是主方法,是将XML文档写入到一个新的文件
public static void main(String[] args) {
try {
String uri = "c://a//NewBook.xml";
ArrayList list = getBookArrayList(uri);
FileWriter fs = new FileWriter("output.xml");//创建流对象
fs.write("<?xml version = /"1.0/"?>");
fs.write("/n<library>");
try {
for (int count = 0; count < list.size(); count++) {
Book temp = (Book) list.get(count);
System.out.println("第" + (count + 1) + "本书:");
fs.write("/n<book>/n");
if (temp.getBookTitle() != null) {
System.out.println("书名:" + temp.getBookTitle());
fs.write("<booktitle>");
fs.write(temp.getBookTitle());
fs.write("</booktitle>/n");
}
if (temp.getAuthor() != null) {
System.out.println("作者:" + temp.getAuthor());
fs.write("<author>");
fs.write(temp.getAuthor());
fs.write("</author>/n");
}
if (temp.getPrice() != null) {
System.out.println("价格:" + temp.getPrice());
fs.write("<price>");
fs.write(temp.getPrice());
fs.write("</price>");
}
fs.write("/n</book>");
}
fs.write("/n</library>");
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.out.println(ex.getStackTrace());
}
System.out.println("所有数据已经成功写入output.xml文件,请查看!");
fs.close();//★★流的关闭
} catch (FactoryConfigurationError e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
=======================================================================
【第2种】C#对XML的解析
㈠XmlDocument对象表示XML整个文档
DocumentElement 属性:获取根节点
ChildNodes 属性:获取所有子节点
Load()方法:读取整个XML的结构
㈡XmlNode对象表示XML文件的单个节点
InnerText 属性:当前节点的值
Name属性:当前节点的名字
ChildNodes 属性:当前节点的所有子节点
例如,下面的一小部分代码:
//导入命名空间
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace ReadXml
{
class Program
{
XmlDocument myXml = new XmlDocument(); //创建XmlDocument对象
myXml.Load("Student.xml");//开始解析XML文件
XmlNode student = myXml.DocumentElement;//获取根节点
foreach (XmlNode node in student.ChildNodes )//通过循环,对子节点进行解析
{
switch (node.Name)
{
case "Name":
Console.WriteLine("姓名:{0}",node.InnerText); //将节点的数据显示出来
break;
case "Age":
Console.WriteLine("年龄:{0}", node.InnerText);
break;
case "Hobby":
Console.WriteLine("爱好:{0}", node.InnerText);
break;
}
}
}
}
=======================================================================
【第3种】javascript对XML的解析
== note.xml ==
<?xml version="1.0" encoding="gb2312" ?>
<note>
<from>小章</from>
<to>小林</to>
<message>周末一起去吃火锅呀</message>
</note>
上面有一个简单的XML文件,现在要通过javascript去解析它
== note.htm ==
<html>
<head>
<script type="text/javascript" for="window" event="onload">
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM") //这一步是创建Ajax的对象
xmlDoc.async="false"
xmlDoc.load("note.xml") //这里是在解析XML文件了
nodes=xmlDoc.documentElement.childNodes //获取所有的节点,用集合去接收
a1.innerText=nodes.item(0).text //分别取值
a2.innerText=nodes.item(1).text
a3.innerText=nodes.item(2).text
</script>
</head>
<body bgcolor="yellow">
<h1>Note</h1>
<b>To:</b>
<span id="a1"></span>
<br />
<b>From:</b>
<span id="a2"></span>
<b><span id="a3"></span></b>
</body>
</html>
====================================
下面是页面加载XML的数据后显示的内容
Note
To: 小章
From: 小林
周末一起去吃火锅呀
=======================================================================
【第4种】Ajax对XML的解析
== SelectListServlet.java ==
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
String provinceid=request.getParameter("province"); //获取异步提交过来的数据
String sql="select * from city where provinceid="+provinceid;
CityBo bo=new CityBo();
List list=bo.selectCityList(sql); //通过SQL语句查询数据库
//** 通过查询的结果链接成XML字符串 **
StringBuffer buffer=new StringBuffer("<?xml version=/"1.0/" encoding=/"GB2312/" ?><result>");
for(int i=0;i<list.size();i++){
buffer.append("<cityname>");
buffer.append((String)list.get(i));
buffer.append("</cityname>");
}
buffer.append("</result>");
out.print(buffer.toString());//通过out.print将XML文档发送到Ajax客户端
out.close();
}
== selectList.html ==
<script type="" language="javascript">
var xmlHttp=false;
//创建Ajax的对象
function createXMLHttpRequest(){
if(window.ActiveXObject){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}else{
xmlHttp=new XMLHttpRequest();
}
var url="selectlistservlet?province=湖南省"; //定义异步提交的URl,将 "湖南省" 作为查询条件
xmlHttp.open("get",url,true); //定义异步提交的方式
xmlHttp.onreadystatechange=processResponse; //定义回调函数
xmlHttp.send(); //开始异步提交
}
//处理异步提交回来的数据的函数
function processResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
updateList();
}
}
}
//解析XML的函数
function updateList(){
var city=document.getElementById("city"); //获取下拉框的对象
var res=xmlHttp.responseXML.getElementsByTagName("cityname"); //★★responseXML属性将加载服务端发送过来的XML文件,
//getElementsByTagName方法加载XML中的元素,返回的是个集合
var option=null;
for(i=0;i<res.length;i++){
option=document.createElement("option");
option.appendChild(document.createTextNode(res[i].firstChild.nodeValue));//★★res[i].firstChild.nodeValue是获取第i+1个元素中的数据
city.appendChild(option);
}
}
</script>