1. 程式人生 > >Android 解析、修改xml檔案

Android 解析、修改xml檔案

一、DOM解析XML檔案
public static void main(String[] args) {
    File file = new File("d:\\WordChronos.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder docbuder;
    try {
        docbuder = dbf.newDocumentBuilder();
        Document doc = docbuder.parse(file);
        NodeList nl = doc.getElementsByTagName_r("Set");
        for(int i = 0;i < nl.getLength();i ++){
            doc.getElementsByTagName_r("Time1").item(0).getFirstChild().setNodeValue("2010-10-30");
            String s1 = doc.getElementsByTagName_r("Time1").item(0).getFirstChild().getNodeValue();
            String s2 = doc.getElementsByTagName_r("Time2").item(0).getFirstChild().getNodeValue();
            String s3 = doc.getElementsByTagName_r("Time3").item(0).getFirstChild().getNodeValue();
            String s4 = doc.getElementsByTagName_r("Music1").item(0).getFirstChild().getNodeValue();
            System.out.println(s1 + ";" + s2 + ";" + s3 + ";" + s4);
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

二、DOM4J解析XML檔案
SAXReader reader = new SAXReader();   
Document document;
try {
    document = reader.read(new File("d:\\WordChronos.xml"));
    Element root = ((org.dom4j.Document) document).getRootElement();   
    List<Element> worktimes = root.elements("Set");   
    for (Element worktime : worktimes) {  
        
        worktime.element("Time1").setText("07:00");    
        worktime.element("Time2").setText("08:00"); 
        worktime.element("Time3").setText("09:00"); 
        worktime.element("Music1").setText("我知道我愛你.mp3"); 

        
        time1 = worktime.element("Time1").getText();    
        time2 = worktime.element("Time2").getText(); 
        time3 = worktime.element("Time3").getText(); 
        musicPath1 = worktime.element("Music1").getText();  
        System.out.println(time1+"\t"+time2+"\t"+time3+"\t"+musicPath1);
    }   
    XMLWriter writer = new XMLWriter(new FileWriter("d:\\WordChronos.xml"));   
    writer.write(document);   
    writer.close(); 
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (DocumentException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}   

三、Android自帶的pull解析方式 ********************************xml檔案格式***************************************
<?xml version="1.0" encoding="utf-8" ?>
<LunarFeast>
  <Feast>
    <Date>0101</Date>
    <Content>春節</Content>
  </Feast>
  <Feast>
    <Date>0115</Date>
    <Content>元宵節</Content>
  </Feast>
  <Feast>
    <Date>0202</Date>
    <Content>青龍節</Content>
  </Feast>
  。。。。。。。
 
</LunarFeast>
**********************************************************************************
//解析XML檔案
public List<Message> parser2(){
    //引用資源中的xml檔案,如下方式獲取:
    //XmlPullParser parser = this.getResources().getXml(R.xml.solarfeastfile);

    //引用sdcard裡面的xml檔案,如下方式獲取
    XmlPullParser parser = Xml.newPullParser();
    InputStream is = new FileInputStream(path);
    parser.setInput(is,"utf-8");

    try {
        int eventType = parser.getEventType();
        Message currentMessage = null;
        boolean done = false;
        while(eventType!= XmlPullParser.END_DOCUMENT && !done){
            String name = null;
            switch(eventType){
            case XmlPullParser.START_DOCUMENT:
                message2 = new ArrayList<Message>();
                break;
            case XmlPullParser.START_TAG:
                name = parser.getName();
                if(name.equalsIgnoreCase("Feast")){
                    currentMessage = new Message();
                }else if(currentMessage != null){
                    if(name.equalsIgnoreCase("Date")){
                        currentMessage.setDate(parser.nextText());
                    }else if(name.equalsIgnoreCase("content")){
                        currentMessage.setContent(parser.nextText());
                    }
                }
                break;
            case XmlPullParser.END_TAG:
                name = parser.getName();
                if(name.equalsIgnoreCase("Feast") && currentMessage != null){
                    message2.add(currentMessage);
                }
                break;
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return message2;
}
四、SAX引擎讀取xml檔案: ************************************xml檔案格式*********************************
<?xml version="1.0" encoding="utf-8" ?> 
<products>
<product>
  <id>10</id> 
  <name>電腦</name> 
  <price>2067.25</price> 
</product>
<product>
  <id>20</id> 
  <name>微波爐</name> 
  <price>520</price> 
</product>
<product>
  <id>30</id> 
  <name>洗衣機</name> 
  <price>2400</price> 
</product>
</products>

******************************************************************************** 1、繼承DefaultHandler類,處理5個分析點的事件
public class XML2Product extends DefaultHandler{
    private List<Product> products;
    private Product product;
    private StringBuffer buffer = new StringBuffer();

    public List<Product> getProducts(){
        return products;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException{
        buffer.append(ch, start, length);
        super.characters(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException{
        if (localName.equals("product")){
            products.add(product);
        }else if (localName.equals("id")){
            product.setId(Integer.parseInt(buffer.toString().trim()));
            buffer.setLength(0);
        }else if (localName.equals("name")){
            product.setName(buffer.toString().trim());
            buffer.setLength(0);
        }else if (localName.equals("price")){
            product.setPrice(Float.parseFloat(buffer.toString().trim()));
            buffer.setLength(0);
        }
        super.endElement(uri, localName, qName);
    }
    @Override
    public void startDocument() throws SAXException{
        products = new ArrayList<Product>();
    }

    @Override
    public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException{
        if (localName.equals("product")){
            product = new Product();
        }
        super.startElement(uri, localName, qName, attributes);
    }
}
2、引用上面的類,將解析的內容顯示出來
@Override
public void onFileItemClick(String filename){
    try{
        if (!filename.toLowerCase().endsWith("xml"))
            return;
        FileInputStream fis = new FileInputStream(filename);
        XML2Product xml2Product = new XML2Product();
        android.util.Xml.parse(fis, Xml.Encoding.UTF_8, xml2Product);

        List<Product> products = xml2Product.getProducts();
        String msg = "共" + products.size() + "個產品\n";
        for (Product product : products){
            msg += "id:" + product.getId() + "  產品名:" + product.getName() + "  價格:" + product.getPrice() + "\n";
        }
        new AlertDialog.Builder(this).setTitle("產品資訊").setMessage(msg).setPositiveButton("關閉", null).show();
    }
    catch (Exception e){

    }
}