当前位置: 首页 > 图文教程 > XML家族 > XML > xml解析的四种方式

XML
XML简易教程之四
XML与HTML的结合(上)
XML与HTML的结合(下)
XML入门的常见问题(一)
XML入门的常见问题(二)
XMLHTTP资料
什么是XML
什么是 XML Web Service
XML正在接管Web服务 成为SOA的基础
怎么样在网页上读取远程xml的数据
XML教程—编写结构完整的XML文档
读写xml文件的2个小函数
XML文档的基本操作
初学者如何开发出一个高质量的J2EE系统
优化 JavaScript 代码
自动更新程序的设计框架
使Firefox对XML的处理兼容IE的节点处理方法
WML学习之四 锚和任务
WML学习之五 显示表单
WML学习之六 事件

XML 中的 xml解析的四种方式


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 127 ::
收藏到网摘: n/a

待解析的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<user>
<name>admin</name>
<sex>123</sex>
<age>123</age>

<name>admin</name>
<sex>123</sex>
<age>123</age>

</user>
第一种方式sax 需要自己处理

文件1 package com.norteksoft.xml;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class ParseUserXml {


private static String XMLPATH ="";
private static ParseUserXml p=new ParseUserXml();

private ParseUserXml()
{


}
public static ParseUserXml getInstance()
{

XMLPATH =p.getClass().getResource("UserInfo.xml").getPath();
System.out.println("filePath:=="+XMLPATH);
System.out.println("\n");
return p;
}

public String pasrseXML() throws ParserConfigurationException,
SAXException, IOException

{
File xmlfile = new File(XMLPATH);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
SAXParser saxParse = factory.newSAXParser();

// XmlHandler xmlHandler=new XmlHandler(user);

saxParse.parse(xmlfile, new SaxXmlHandler());

// System.out.println("返回值为:\n"+xmlHandler.getUser());

return null;
}
}

文件2

package com.norteksoft.xml;

import java.util.Stack;

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

public class SaxXmlHandler extends DefaultHandler

{
Stack tags=new Stack();

public void startDocument() throws SAXException
{
System.out.println("~~~~~~~~~开始解析文档~~~~~~~~~~~~~");
super.startDocument();
}

public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
System.out.println("-----开始解析"+qName+"----");
tags.push(qName);
super.startElement(uri, localName, qName, attributes);
}

public void characters(char[] ch, int start, int length) throws SAXException
{
String value=new String(ch,start,length);
String tag=(String) tags.peek();
if(tag.equals("name"))
{
System.out.println("name="+value);
}
else if (tag.equals("age"))
{
System.out.println("age="+value);
}
else if(tag.equals("sex"))
{
System.out.println("sex="+value);
}
else
{
System.out.println(";value="+";"+tag+"没有匹配到!");
}
super.characters(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
System.out.println("-----结束解析"+qName+"----");

tags.pop();

super.endElement(uri, localName, qName);
}
public void endDocument() throws SAXException
{
System.out.println("~~~~~~~~~结束解析文档~~~~~~~~~~~~~");
super.endDocument();
}
}
方式2:dom 解析

package com.norteksoft.xml;

import java.io.File;
import java.io.IOException;
import java.net.URL;

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

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

public class MyDomXmlReader
{
static User[] users;

public MyDomXmlReader()
{
super();

}

private static void parseXmlWithEception() throws ParserConfigurationException, SAXException, IOException
{
URL url=MyDomXmlReader.class.getResource("UserInfo.xml");

File file=new File(url.getPath());

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();

Document doc =builder.parse(file);

NodeList nodes=doc.getElementsByTagName("user");
users=new User[nodes.getLength()];
String name=null;
String age=null;
String sex=null;
System.out.println("begin");
for(int i=0;i<nodes.getLength();i++)
{
System.out.println("i===="+i+"-------");

NodeList nl=((Node)nodes.item(i)).getChildNodes();

for(int j=0;j<nl.getLength();j++)
{

System.out.println("j=="+j+"\n "+nl.item(j).getNodeName());
}
// String temp= ((Node)nodes.item(i)).getChildNodes().getLength()+";";

// System.out.println("temp====="+temp);

name=doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();

// System.out.println("name="+name);

age=doc.getElementsByTagName("age").item(i).getFirstChild().getNodeValue();
// System.out.println("age="+age);

sex=doc.getElementsByTagName("sex").item(i).getFirstChild().getNodeValue();
// System.out.println("sex="+sex);

users=new User(age,name,sex);


}
System.out.print("end");


}
public static void parseXml()
{
try
{
parseXmlWithEception();
}catch (Exception e)
{
e.printStackTrace();
}
}

public static User[] returnValue()
{
parseXml();
return users;
}


}

方式3: JDom

package com.norteksoft.xml;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class MyJDomXml
{

public MyJDomXml()
{
super();
}

public static void parseXmlThowException() throws JDOMException, IOException
{
URL url=MyJDomXml.class.getResource("UserInfo.xml");

File file=new File(url.getPath());

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(file);

Element root = doc.getRootElement();

List allChildren = root.getChildren();

for(int i=0;i<allChildren.size();i++)
{
Element foo=(Element) allChildren.get(i);

System.out.println(foo.getName()+"==="+foo.getName());

System.out.println("name="+foo.getChild("name").getText());
System.out.println("age="+foo.getChild("age").getText());
System.out.println("sex="+foo.getChild("sex").getText());
}


}


public static void parseXml()
{
try {
parseXmlThowException();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


方式4 dom4j

package com.norteksoft.xml;

import java.io.File;
import java.net.MalformedURLException;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class MyDom4JXmlReader
{

public MyDom4JXmlReader()
{
super();

}

private static void parseXmlThrowException() throws MalformedURLException, DocumentException
{
String path=MyDom4JXmlReader.class.getResource("UserInfo.xml").getPath();

File f = new File(path);

SAXReader reader = new SAXReader();

Document doc = reader.read(f);

Element root=doc.getRootElement();

Element foo;

List list=root.elements();
for(int i=0;i<list.size();i++)
{

foo=(Element) list.get(i);
System.out.println("name="+foo.elementText("name"));
System.out.println("age="+foo.elementText("age"));
System.out.println("sex="+foo.elementText("sex"));


}
/*for(Iterator it= root.elementIterator("user");it.hasNext();)
{
foo=(Element) it.next();

System.out.println("name="+foo.elementText("name"));
System.out.println("age="+foo.elementText("age"));
System.out.println("sex="+foo.elementText("sex"));


}*/


}
public static void praseXml()
{

try {
parseXmlThrowException();
} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}