用java读取xml文件的四种方法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用java读取xml文件的四种方法
默认分类2008-09-06 22:37:04 阅读15 评论0 字号:大中小订阅
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>**省XX县XX镇XX路X段XX号</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>**省XX市XX乡XX村XX组</ADDR>
</VALUE>
</RESULT>
第一种DOM 实现方法
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 MyXMLReader2DOM {
public static void main(String arge[]) {
long lasting = System.currentTimeMillis();
try {
File f = new File("data_10k.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList nl = doc.getElementsByTagName("VALUE");
for (int i = 0; i < nl.getLength(); i++) {
System.out.print("车牌号码:"+
doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue( ));
System.out.println("车主地址:"
+
doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValu e());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二种,DOM4J实现方法
import java.io.*;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.*;
public class MyXMLReader2DOM4J {
public static void main(String arge[]) {
long lasting = System.currentTimeMillis();
try {
File f = new File("data_10k.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(f);
Element root = doc.getRootElement();
Element foo;
for (Iterator i = root.elementIterator("VALUE");
i.hasNext();) {
foo = (Element) i.next();
System.out.print("车牌号码:" + foo.elementText("NO"));
System.out.println("车主地址:" +
foo.elementText("ADDR"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第三种JDOM实现方法
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.*;
public class MyXMLReader2JDOM {
public static void main(String arge[]) {
long lasting = System.currentTimeMillis();
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("data_10k.xml"));
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for (int i = 0; i < allChildren.size(); i++) {
System.out.print("车牌号码:" + ((Element) allChildren.get(i)).getChild("NO").getText());
System.out.println("车主地址:"
+ ((Element)
allChildren.get(i)).getChild("ADDR").getText());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第四种SAX实现方法
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLReader2SAX extends DefaultHandler {
java.util.Stack tags = new java.util.Stack();
public MyXMLReader2SAX() {
super();
}
public static void main(String args[]) {
long lasting = System.currentTimeMillis();
try {
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
MyXMLReader2SAX reader = new MyXMLReader2SAX();
sp.parse(new InputSource("data_10k.xml"), reader);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("运行时间:" + (System.currentTimeMillis() - lasting) + "毫秒");
}
public void characters(char ch[], int start, int length) throws SAXException {
String tag = (String) tags.peek();
if (tag.equals("NO")) {
System.out.print("车牌号码:" + new String(ch, start, length));
}
if (tag.equals("ADDR")) {
System.out.println("地址:"+ new String(ch, start, length));
}
}
public void startElement(String uri, String localName, String qName, Attributes attrs) {
tags.push(qName);
}
}
已知有一个XML文件(bookstore.xml)如下:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
</bookstore>
1、往<bookstore>节点中插入一个<book>节点:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("bookstore.xml");
XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
XmlElement xe1=xmlDoc.CreateElement("book");//创建一个<book>节点
xe1.SetAttribute("genre","李赞红");//设置该节点genre属性
xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性
XmlElement xesub1=xmlDoc.CreateElement("title");
xesub1.InnerText="CS从入门到精通";//设置文本节点
xe1.AppendChild(xesub1);//添加到<book>节点中
XmlElement xesub2=xmlDoc.CreateElement("author");
xesub2.InnerText="候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement("price");
xesub3.InnerText="58.3";
xe1.AppendChild(xesub3);
root.AppendChild(xe1);//添加到<bookstore>节点中
xmlDoc.Save("bookstore.xml");
//===============================================
结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
</bookstore>
2、修改节点:将genre属性值为“李赞红“的节点的genre值改为“update李赞红”,将该节点的子节点<author>的文本修改为“亚胜”。
XmlNodeList nodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点
foreach(XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
if(xe.GetAttribute("genre")=="李赞红")//如果genre属性值为“李赞红”
{
xe.SetAttribute("genre","update李赞红");//则修改该属性为“update李赞红”
XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//遍历
{
XmlElement xe2=(XmlElement)xn1;//转换类型
if(=="author")//如果找到
{
xe2.InnerText="亚胜";//则修改
break;//找到退出来就可以了
}
}
break;
}
}
xmlDoc.Save("bookstore.xml");//保存。
//==================================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="update李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>亚胜</author>
<price>58.3</price>
</book>
</bookstore>
3、删除<book genre="fantasy" ISBN="2-3631-4">节点的genre属性,删除<book genre="update李赞红" ISBN="2-3631-4">节点。
XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildNodes;
foreach(XmlNode xn in xnl)
{
XmlElement xe=(XmlElement)xn;
if(xe.GetAttribute("genre")=="fantasy")
{
xe.RemoveAttribute("genre");//删除genre属性
}
else if(xe.GetAttribute("genre")=="update李赞红")
{
xe.RemoveAll();//删除该节点的全部内容
}
}
xmlDoc.Save("bookstore.xml");
//===========================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book>
</book>
</bookstore>
4、显示所有数据。
XmlNode xn=xmlDoc.SelectSingleNode("bookstore");
XmlNodeList xnl=xn.ChildNodes;
foreach(XmlNode xnf in xnl)
{
XmlElement xe=(XmlElement)xnf;
Console.WriteLine(xe.GetAttribute("genre"));//显示属性值
Console.WriteLine(xe.GetAttribute("ISBN"));
XmlNodeList xnf1=xe.ChildNodes;
foreach(XmlNode xn2 in xnf1)
{
Console.WriteLine(xn2.InnerText);//显示子节点点文本
}
}
1.有很多时候我们需要将相关动态的信息保存到XML文件中去,那么我们就可以动态输入相关信息。
特别是针对数据库方面的操作的时候就非常地灵活。
那我现在假如项目中的操作数据库的包为model里面存放了我们的XML文件db.xml 现在来看看如何解析出来相关的数据来调用。
第一个类:
package model;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.Properties;
//使用DefaultHandler的好处是不必陈列出所有方法,
public class ConfigParser extends DefaultHandler {
////定义一个Properties 用来存放 dbhost dbuser dbpassword的值
private Properties props;
private String currentSet;
private String currentName;
private StringBuffer currentValue = new StringBuffer();
//构建器初始化props
public ConfigParser() {
this.props = new Properties();
}
public Properties getProps() {
return this.props;
}
//定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来.
public void startElement(String uri, String localName, String qName, Attributes attributes)throws SAXException {
currentValue.delete(0, currentValue.length());
this.currentName =qName;
//这里是将<xxx></xxx>之间的值加入到currentValue
public void characters(char[] ch, int start, int length) throws SAXException {
currentValue.append(ch, start, length);
}
//在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中
public void endElement(String uri, String localName, String qName) throws SAXException {
props.put(qName.toLowerCase(), currentValue.toString().trim());
}
}
可以直接拷贝过来用了。
第二个类:
package model;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import .URL;
public class ParseXML{
//定义一个Properties 用来存放 dbhost dbuser dbpassword的值
private Properties props;
//这里的props
public Properties getProps() {
return this.props;
}
public void parse(String filename) {
//将我们的解析器对象化
ConfigParser handler = new ConfigParser();
//获取SAX工厂对象
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
//获取SAX解析
SAXParser parser=null;
try {
parser = factory.newSAXParser();
} catch (Exception e1) {
e1.printStackTrace();
URL confURL = null;
//得到配置文件myenv.xml所在目录. tomcat中是在WEB-INF/classes
//下例中BeansConstants是用来存放xml文件中配置信息的类,可以自己代替或定义
try{
confURL = ParseXML.class.getClassLoader().getResource(filename);
//只需要将我们所需要的XML文件名字输入进去就可以了!
}catch(Exception e){
System.out.print(e.toString());
}
try
{ //将解析器和解析对象myenv.xml联系起来,开始解析
parser.parse(confURL.toString(), handler);
//获取解析成功后的属性以后我们其他应用程序只要调用本程序的props就可以提取出属性名称和值了
props = handler.getProps();
}catch(Exception e){
System.out.println(e.toString());
}finally{
factory=null;
parser=null;
handler=null;
}
}
}
下面是我们所需要调用的XML文件内容:
<myenv>
<datasource>
<dbhost>localhost</dbhost>
<dbname>tianya_speed_test</dbname>
<dbuser>root</dbuser>
<dbpassword>321</dbpassword>
</datasource>
</myenv>
现在需要将其中的相关内容读取出来。
包括数据库主机地址,数据库名字,用户名及密码好了,现在准备工作已经都做完了。
现在就可以来想想如何来调用我们刚才解析出来的内容喽:
public void initVariable(){
ParseXML test = new ParseXML();
test.parse("model/db.xml");//表示实际的XML文件位置,如果没有找到就报空指针异常!
}catch(Exception e){
System.out.print(e.toString());
}
Properties pro = test.getProps();//获取到PRO对象然后用它去调用相关的属性!
dbServer = pro.getProperty("dbhost");//相当于Python中的字典类型。
dbName = pro.getProperty("dbname");
dbUser = pro.getProperty("dbuser");
dbPwd = pro.getProperty("dbpassword");
}
tcp.validnode_checking=yes
#允许访问的ip
tcp.invited_nodes=(ip1,ip2,……)
#不允许访问的ip
tcp.excluded_nodes=(ip1,ip2,……)
好了,现在我们就只需要手工来修改XML就可以了。
以后在做项目过程中如果需要用XML来配置数据库或其他的相关信息就可以了用这个方法哦。
比较简单而且实用!。