您的位置:首页 > 运维架构

Xml解析、properties文件读取

2012-02-20 23:43 274 查看
用Jdk中的类解析xml


xml/plant_catalog.xml

<?xml
version="1.0"
encoding="ISO-8859-1"?>

<!-- Edited with XML Spy v2007 (http://www.altova.com) -->

<CATALOG>

<PLANT>

<COMMON>Bloodroot</COMMON>

<BOTANICAL>Sanguinaria canadensis</BOTANICAL>

<ZONE>4</ZONE>

<LIGHT>Mostly Shady</LIGHT>

<PRICE>$2.44</PRICE>

<AVAILABILITY>031599</AVAILABILITY>

</PLANT>

<PLANT>

<COMMON>Columbine</COMMON>

<BOTANICAL>Aquilegia canadensis</BOTANICAL>

<ZONE>3</ZONE>

<LIGHT>Mostly Shady</LIGHT>

<PRICE>$9.37</PRICE>

<AVAILABILITY>030699</AVAILABILITY>

</PLANT>

<PLANT>

<COMMON>Marsh Marigold</COMMON>

<BOTANICAL>Caltha palustris</BOTANICAL>

<ZONE>4</ZONE>

<LIGHT>Mostly Sunny</LIGHT>

<PRICE>$6.81</PRICE>

<AVAILABILITY>051799</AVAILABILITY>

</PLANT>

</CATALOG>

 

DOMTest.java

package dom;

 

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.*;

import java.io.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

 

public
class DOMTest

{

private
static
final String PLANT="PLANT";

private
static
final String COMMON="COMMON";

private
static
final String BOTANIC="BOTANICAL";

private
static
final String PRICE="PRICE";

private
static
final String LIGHT="LIGHT";

private
static
final String ZONE="ZONE";

private
static
final String AVAILABILITY="AVAILABILITY";

 

public
static
void main(String[] args)
throws Exception

{

 

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

DocumentBuilder db=dbf.newDocumentBuilder();

FileInputStream fis=new FileInputStream("./xml/plant_catalog.xml");

Document doc=db.parse(fis);

Element root=doc.getDocumentElement();

NodeList plantList=root.getElementsByTagName(PLANT);

 

NodeList common=root.getElementsByTagName(COMMON);

NodeList botanic=root.getElementsByTagName(BOTANIC);

NodeList price=root.getElementsByTagName(PRICE);

NodeList light=root.getElementsByTagName(LIGHT);

NodeList zone=root.getElementsByTagName(ZONE);

NodeList availability=root.getElementsByTagName(AVAILABILITY);

Double sum=new Double(0.0);

 

for(int i=0;i<plantList.getLength();i++)

{

Node plant=plantList.item(i);

Plant p=new Plant();

p.setAvailability(availability.item(i)

.getFirstChild().getTextContent());

p.setZone(zone.item(i)

.getFirstChild().getTextContent());

p.setLight(light.item(i)

.getFirstChild().getTextContent());

p.setPrice(price.item(i)

.getFirstChild().getTextContent());

p.setBotanincal(botanic.item(i)

.getFirstChild().getTextContent());

p.setCommon(common.item(i)

.getFirstChild().getTextContent());

System.out.println(p);

 

System.out.println("p.getPrice():"+p.getPrice());

String strPric=p.getPrice();

Double pric=new Double((strPric.substring(1,strPric.length())));

sum=sum.doubleValue()+pric.doubleValue();

}

System.out.println("------------总价格--------------");

System.out.println("sum price:"+sum);

 

write();

System.out.println("----------------------my_plant.xml write success");

}

 

//使用dom生成xml

public
static
void write()
throws Exception

{

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

DocumentBuilder db=dbf.newDocumentBuilder();

//在内存中创建了dom模型

Document doc=db.newDocument();

//创建元素

Element root=doc.createElement("CATALOG");

Element p=doc.createElement("PLANT");

Plant plant=new Plant();

plant.setAvailability("p1-boni");

plant.setCommon("p1-common");

plant.setBotanincal("p1-botanincal");

plant.setLight("p1-light");

plant.setPrice("p1-price");

plant.setZone("p1-zone");

 

Element common=doc.createElement("COMMON");

Text commonText=(Text)doc.createTextNode(plant.getCommon());

common.appendChild(commonText);

 

Element botanical=doc.createElement("BOTANICAL");

Text botanicalText=(Text)doc.createTextNode(plant.getBotanincal());

botanical.appendChild(botanicalText);

 

Element price=doc.createElement("PRICE");

Text priceText=(Text)doc.createTextNode(plant.getPrice());

price.appendChild(priceText);

 

Element light=doc.createElement("LIGHT");

Text lightText=(Text)doc.createTextNode(plant.getLight());

light.appendChild(lightText);

 

Element zone=doc.createElement("ZONE");

Text zoneText=(Text)doc.createTextNode(plant.getZone());

zone.appendChild(zoneText);

 

Element availability=doc.createElement("AVAILABILITY");

Text availabilityText=(Text)doc.createTextNode(plant.getAvailability());

availability.appendChild(availabilityText);

 

p.appendChild(common);

p.appendChild(botanical);

p.appendChild(price);

p.appendChild(light);

p.appendChild(zone);

p.appendChild(availability);

root.appendChild(p);

doc.appendChild(root);

 

TransformerFactory tff=TransformerFactory.newInstance();

Transformer tf=tff.newTransformer();

DOMSource ds=new DOMSource(doc);

FileOutputStream fos=new FileOutputStream("./xml/my_plant.xml");

 

StreamResult sr=new StreamResult(fos);

//System.out.println(sr);

tf.transform(ds,sr);

fos.flush();

fos.close();

}

}

 

class Plant

{

private String common;

private String botanincal;

private String zone;

private String light;

private String price;

private String availability;

    …………set、get方法…………

@Override

public String toString()

{

return
"Plant is [commont="+common+",botanincal="+botanincal+",zone="

+zone+",light="+light+",price="+price+",availability="

+availability+"]";

}

}

 

Properties文件的读取


config.properties

port = 9999

ip = 127.0.0.1

picname = clock.jpg

username = scott

password = luowei

 

PropertiesTest.java

package pros;

 

import java.util.Properties;

import java.io.*;

 

public
class PropertiesTest

{

public
static
void main(String []args)
throws Exception

{

Properties pros=new Properties();

pros.setProperty("port","8888");

pros.setProperty("ip","localhost");

Object value=pros.setProperty("port","9999");

System.out.println(pros.getProperty("port"));

System.out.println(value);

 

for(Object obj:pros.keySet())
//遍历

{

String key=(String)obj;

System.out.println(key+" => "+pros.getProperty(key));

}

 

System.err.println("++++++++++++++++++++++++++");

Properties pro1 =
new Properties();

FileInputStream fis =
new FileInputStream("./pros/config.properties");

InputStream is = PropertiesTest.class.getResourceAsStream("/pros/config.properties");

pro1.load(is);

for(Object obj:pro1.keySet())
//遍历

{

String key=(String)obj;

System.out.println(key+" => "+pro1.getProperty(key));

}

}

 

}

 

Sax方式解析xml


MatchTest.java

package sax;

import java.io.*;

import java.util.Date;

import java.util.*;

import org.xml.sax.*;

import org.xml.sax.helpers.*;

import javax.xml.parsers.*;

 

public
class MatchTest

{

private List<Match> list;

public MatchTest()

{

list=new ArrayList<Match>();

}

public
void setList(List<Match> list)

{

this.list=list;

}

public List<Match> getList()

{

return
this.list;

}

 

public
static
void main(String []args)
throws Exception

{


        //获得sax解析实例

SAXParserFactory sf=SAXParserFactory.newInstance();

SAXParser parser=sf.newSAXParser();

FileInputStream fis=new FileInputStream("./xml/result.xml");

MatchHandler handler=new MatchHandler();


        //解析


parser.parse(fis,handler);

List<Match> list=handler.getList();

for(Match match:list)

{

System.out.println(match.getFirstTeam().getName()+"\tVS\t @ "

+match.getSecondTeam().getName()+" @ "+match.getDate());

}

}

 

}

 

//解析比赛(Match)的类


class MatchHandler extends DefaultHandler

{

public
static
final String TEAM="team";

public
static
final String MATCH="match";

public
static
final String DATE="date";

private List<Match> matchList=new ArrayList<Match>();

private Match lastMatch;

private String lastValue;

private Map<String,Object> eleMap=new HashMap<String,Object>();

 

public List<Match> getList()

{

return
this.matchList;

}

 

@Override

public
void characters(char[] ch,
int start,
int length)
throws SAXException

{

String eleString=new String(ch,start,length).trim();

if(eleString.length()==0)

{

return;

}

lastValue=eleString;

}

 

@Override

public
void startDocument()
throws SAXException

{

super.startDocument();

}

 

@Override

public
void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException

{

String eleName=qName;

if(eleName.equals(MATCH))

{

Match match=(Match)extract(MATCH,lastValue);
//创建任意类型的实例,自已提供

matchList.add(match);

lastMatch=match;

}

}

 

@Override

public
void endElement(String uri, String localName, String qName)
throws SAXException

{

String eleName=qName;

if(eleName.equals(TEAM))

{

Team team=(Team)extract(TEAM,lastValue);

//System.out.println("---------------"+lastValue);

Object object=eleMap.get(TEAM);

if(object!=null)

{

lastMatch.setSecondTeam(team);

eleMap.remove(TEAM);

}

else

{

eleMap.put(TEAM,team);

lastMatch.setFirstTeam(team);

}

}

if(eleName.equals(DATE))

{

Date date=(Date)extract(DATE,lastValue);

lastMatch.setDate(date);

}

}

 

@Override

public
void endDocument()
throws SAXException

{

super.endDocument();

}

 

public
<T> T extract(String type,String value)
//返回任意类型

{

T t=null;

if(type.equals(MATCH))

{

t=(T)
new Match();

}

if(type.equals(TEAM))

{

Team team=new Team();

team.setName(value);

//System.out.println("teamName----------"+team.getName());

t=(T) team;

}

if(type.equals(DATE))

{

//t=(T) new Date(DATE);

String []strings=value.split("-");

Calendar cal=Calendar.getInstance();

cal.set(Integer.parseInt(strings[2]),extractMonth(strings[1]),

Integer.parseInt(strings[0]));

t=(T) cal.getTime();

}

return t;

}

 

public
int extractMonth(String mon)

{

String[] months=new String[]{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

for(int i=0;i<months.length;i++)

{

if(mon.equals(months[i]))

{

return i;

}

}

return
0;

}

}

 

 

class Match

{

private Date date;

private Team firstTeam;

private Team secondTeam;

…………set、get方法…………

 

@Override

public String toString()

{

return
"Match [firstTeam="+firstTeam+" secondTeam="+secondTeam+"]";

}

}

 

class Team

{

private
int score;

private String name;

…………set、get方法…………

@Override

public String toString()

{

return
"Team [score="+score+" name="+name+"]";

}

}

 

result.xml

<?xml
version="1.0"?>

<results
group="A">

<match>

<date>10-Jun-1998</date>

<team
score="2">Brazil</team>

<team
score="1">Scotland</team>

</match>

<match>

<date>10-Jun-1998</date>

<team
score="2">Morocco</team>

<team
score="2">Norway</team>

</match>

</results>

 

Student.xml

<?xml
version="1.0"
encoding="utf-8"?>

<!DOCTYPE students [

<!ELEMENT students (student*)>

<!ELEMENT student (name,age,gender,address)>

<!ELEMENT name (#PCDATA)>

<!ELEMENT age (#PCDATA)>

<!ELEMENT gender (#PCDATA)>

<!ELEMENT address (city,country,street)>

<!ELEMENT city (#PCDATA)>

<!ELEMENT country (#PCDATA)>

<!ELEMENT street (#PCDATA)>

<!ATTLIST student id CDATA "0">

]>


 

<students>

<student
id="1">

<name>jd1108</name>

<age>1</age>

<gender>true</gender>

<address>

<city>Kunshan</city>

<country>China</country>

<street>Xueyuan Rd NO. 828</street>

</address>

</student>

<student
id="2">

<name>briup</name>

<age>5</age>

<gender>false</gender>

<address>

<city>Shanghai</city>

<country>China</country>

<street>Wanrong Rd NO.1188</street>

</address>

</student>

</students>

 

SAXTest.java

package sax;

 

import javax.xml.parsers.*;

import java.io.*;

import org.xml.sax.helpers.DefaultHandler;

import org.xml.sax.SAXException;

import org.xml.sax.Attributes;

 

public
class SAXTest

{

public
static
void main(String[] args)
throws Exception

{

SAXParserFactory sf=SAXParserFactory.newInstance();

SAXParser parser=sf.newSAXParser();

StudentHandler handler=new StudentHandler();

FileInputStream fis=new FileInputStream(new File("./xml/Student.xml"));

parser.parse(fis,handler);

}

}

 

class StudentHandler extends DefaultHandler

{

@Override

public
void characters(char[] ch,
int start,
int length)

{

String eleString=new String(ch,start,length);

System.out.println(eleString.trim());

}

 

@Override

public
void startDocument()
throws SAXException

{

System.out.println("<?xml vrsion='1.0' encoding='utf-8'/>");

}

 

@Override

public
void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException

{

String eleName=qName;

System.out.println("<"+eleName+">");

}

 

@Override

public
void endElement(String uri, String localName, String qName)
throws SAXException

{

String eleName=qName;

System.out.println("</"+eleName+">");

}

 

@Override

public
void endDocument()
throws SAXException

{

System.out.println("xml processing finish");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: