Java-Java对XML的解析及Properties文件的读取

用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;
    …………setget方法…………
    @Override
    public String toString()
    {
        return "Plant is [commont="+common+",botanincal="+botanincal+",zone="
                +zone+",light="+light+",price="+price+",availability="
                +availability+"]";
    }
}

Stax下用8种方式操作Xml

package org.itat.stax;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.*;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
public class TestStax {
    @Test
    public void test01() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            XMLStreamReader reader = factory.createXMLStreamReader(is);
            while(reader.hasNext()) {
                int type = reader.next();
                //判断节点类型是否是开始或者结束或者文本节点,之后根据情况及进行处理
                if(type==XMLStreamConstants.START_ELEMENT) {
                    System.out.println(reader.getName());
                } else if(type==XMLStreamConstants.CHARACTERS) {
                    System.out.println(reader.getText().trim());
                } else if(type==XMLStreamConstants.END_ELEMENT) {
                    System.out.println("/"+reader.getName());
                }
            }
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test02() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            XMLStreamReader reader = factory.createXMLStreamReader(is);
            while(reader.hasNext()) {
                int type = reader.next();
                if(type==XMLStreamConstants.START_ELEMENT) {
                    String name = reader.getName().toString();
                    if(name.equals("book")) {
                        System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
                    }
                }
            }
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test03() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            XMLStreamReader reader = factory.createXMLStreamReader(is);
            while(reader.hasNext()) {
                int type = reader.next();
                if(type==XMLStreamConstants.START_ELEMENT) {
                    String name = reader.getName().toString();
                    if(name.equals("title")) {
                        System.out.print(reader.getElementText()+":");
                    }
                    if(name.equals("price")) {
                        System.out.print(reader.getElementText()+"\n");
                    }
                }
            }
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test04() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //基于迭代模型的操作方式
            XMLEventReader reader = factory.createXMLEventReader(is);
            int num = 0;
            while(reader.hasNext()) {
                //通过XMLEvent来获取是否是某种节点类型
                XMLEvent event = reader.nextEvent();
                if(event.isStartElement()) {
                    //通过event.asxxx转换节点
                    String name = event.asStartElement().getName().toString();
                    if(name.equals("title")) {
                        System.out.print(reader.getElementText()+":");
                    }
                    if(name.equals("price")) {
                        System.out.print(reader.getElementText()+"\n");
                    }
                }
                num++;
            }
            System.out.println(num);
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test05() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //基于Filter的过滤方式,可以有效的过滤掉不用进行操作的节点,效率会高一些
            XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(is),
                    new EventFilter() {
                        @Override
                        public boolean accept(XMLEvent event) {
                            //返回true表示会显示,返回false表示不显示
                            if(event.isStartElement()) {
                                String name = event.asStartElement().getName().toString();
                                if(name.equals("title")||name.equals("price"))
                                    return true;
                            }
                            return false;
                        }
                    });
            int num = 0;
            while(reader.hasNext()) {
                //通过XMLEvent来获取是否是某种节点类型
                XMLEvent event = reader.nextEvent();
                if(event.isStartElement()) {
                    //通过event.asxxx转换节点
                    String name = event.asStartElement().getName().toString();
                    if(name.equals("title")) {
                        System.out.print(reader.getElementText()+":");
                    }
                    if(name.equals("price")) {
                        System.out.print(reader.getElementText()+"\n");
                    }
                }
                num++;
            }
            System.out.println(num);
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test06() {
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //创建文档处理对象
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //通过DocumentBuilder创建doc的文档对象
            Document doc = db.parse(is);
            //创建XPath
            XPath xpath = XPathFactory.newInstance().newXPath();
            //第一个参数就是xpath,第二参数就是文档
            NodeList list = (NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
            for(int i=0;i<list.getLength();i++) {
                //遍历输出相应的结果
                Element e = (Element)list.item(i);
                System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test07() {
        try {
            XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
            xsw.writeStartDocument("UTF-8","1.0");
            xsw.writeEndDocument();
            String ns = "http://11:dd";
            xsw.writeStartElement("nsadfsadf","person",ns);
            xsw.writeStartElement(ns,"id");
            xsw.writeCharacters("1");
            xsw.writeEndElement();
            xsw.writeEndElement();
            xsw.flush();
            xsw.close();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } catch (FactoryConfigurationError e) {
            e.printStackTrace();
        }
    }
    @Test
    public void test08() {
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //创建文档处理对象
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //通过DocumentBuilder创建doc的文档对象
            Document doc = db.parse(is);
            //创建XPath
            XPath xpath = XPathFactory.newInstance().newXPath();
            Transformer tran = TransformerFactory.newInstance().newTransformer();
            tran.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            tran.setOutputProperty(OutputKeys.INDENT, "yes");
            //第一个参数就是xpath,第二参数就是文档
            NodeList list = (NodeList)xpath.evaluate("//book[title='Learning XML']", doc,XPathConstants.NODESET);
            //获取price节点
            Element be = (Element)list.item(0);
            Element e = (Element)(be.getElementsByTagName("price").item(0));
            e.setTextContent("333.9");
            Result result = new StreamResult(System.out);
            //通过tranformer修改节点
            tran.transform(new DOMSource(doc), result);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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;
…………setget方法…………
    @Override
    public String toString()
    {
        return "Match [firstTeam="+firstTeam+" secondTeam="+secondTeam+"]";
    }
}
class Team
{
    private int score;
    private String name;
…………setget方法…………
    @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");
    }
}

版权所有,转载请注明出处 luowei.github.io.