Chào mừng đến với Diễn đàn lập trình - Cộng đồng lập trình.
Kết quả 1 đến 3 của 3
  1. #1
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Không thể chỉ cho bạn bởi ... nhưng Kevin nghĩ là bạn nên lấy code sau về sửa lại theo yêu cầu của bạn có lẽ sẽ tốt hơn code bạn viết! (Cũng dùng SAX Parser đấy)


    Mã:
    <?xml version="1.0" encoding="UTF-8" ?><response code="200">    <date>2008-11-07</date>    <title>Exchange rates for 2008-11-07</title>    <rates>        <currency>            <code>EUR</code>            <rate>1.220</rate>        </currency>        <currency>            <code>USD</code>            <rate>1.275</rate>        </currency>    </rates></response>
    Mã:
    package com.javacodegeeks.snippets.core; import java.io.File;import java.util.LinkedList;import java.util.List; import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler; public class ParseXMLFileWithSAX extends DefaultHandler {    private StringBuffer buffer = new StringBuffer();        private static String responseCode;    private static String date;    private static String title;        private static Currency currency;    private static Rates rates;        public static void main(String[] args) throws Exception {                DefaultHandler handler = new ParseXMLFileWithSAX();         SAXParserFactory factory = SAXParserFactory.newInstance();        factory.setValidating(false);                SAXParser parser = factory.newSAXParser();                parser.parse(new File("in.xml"), handler);                System.out.println("Response Code:" + responseCode);        System.out.println("Date:" + date);        System.out.println("Title:" + title);        System.out.println("Rates:");                for (Currency curr : rates.currencies) {            System.out.println("\tCode:" + curr.code + " - Rate:" + curr.rate);        }            }        private static class Currency {        public String code;        public String rate;    }        private static class Rates {        public List<Currency> currencies = new LinkedList<Currency>();    }        @Override    public void startElement(String uri, String localName, String qName,            Attributes attributes) throws SAXException {                buffer.setLength(0);                if (qName.equals("response")) {            responseCode = attributes.getValue("code");        }        else if (qName.equals("date")) {            date = "";        }        else if (qName.equals("title")) {            title = "";        }        else if (qName.equals("rates")) {            rates = new Rates();         }        else if (qName.equals("currency")) {            currency = new Currency();         }            }        @Override    public void endElement(String uri, String localName, String qName)throws SAXException {                if (qName.equals("date")) {            date = buffer.toString();        }        else if (qName.equals("title")) {            title = buffer.toString();        }        else if (qName.equals("currency")) {            rates.currencies.add(currency);        }        else if (qName.equals("code")) {            currency.code = buffer.toString();        }        else if (qName.equals("rate")) {            currency.rate = buffer.toString();        }            }        public void characters(char[] ch, int start, int length) {        buffer.append(ch, start, length);    }}
    Còn tài liệu thì đây (Rất dễ đọc, không cần hiểu tiếng Anh đâu!): _http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html

  2. #2
    Ngày tham gia
    Sep 2015
    Bài viết
    0

    Làm thế nào để gọi lại hàm đọc XML để đọc lại XML( mở thêm chức năng truy vấn )??

    Chào mọi người.
    Hiện tại thì mình đang làm ct đọc file XML. Mình dùng nó để tạo tree trong java. Giờ mình muốn truy vấn dữ liệu cũng dùng lại cách đọc đó nhưng ràng buộc điều kiện đọc để có kết quả mình mong muốn. mà không biết làm như thế nào.
    vd mình có thẻ XML như sau.
    <N id = "01" lop="k1" > Nguyễn văn B</N >
    Mình xây dựng 1 class để đọc XML rồi tạo thành tree.(mỗi node là 1 id.value ).
    giờ mình cần mỗi lần click chọn node thì lấy cái id ( tên node ) rồi truy vấn lại XML để lấy cai tên ( Nguyễn văn B ) . Mình muốn dùng lại cái hàm đọc file XML như lúc tạo nhưng điều kiện lấy là id= tên ID ( trên node).
    Mình k hiểu viết lại hàm đó như thế nào.
    code của mình đọc + tạo cây như sau

    Mã:
    import java.awt.*;import java.io.File;import javax.swing.*;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;  public class BuildTree extends DefaultHandler implements ActionListener{    static JTree tree;     static DefaultMutableTreeNode root,nodeselect;      static DefaultTreeModel model =null ;    String s="";        public  BuildTree()    {        GuiTree();xmlSetUp();    }     public void xmlSetUp() {                 File xmlFile = new File ("\\dbcoi.xml");                   try {                               SAXParserFactory fact = SAXParserFactory.newInstance();                               SAXParser parser = fact.newSAXParser();                               parser.parse(xmlFile, this);/* Mọi người có thể gợi ý doạn này có thể gọi dc hàm đọc tạo tree riêng và hàm truy vấn riêng .cho mình với. *//* Hàm tạo tree cũng có các hàm startElement , endElement... Nhưng câu lệnh của phưong thức tạo tree khác với phưong thức truy vấn. */                         }                    catch (Exception e)                        {                            }         }public void startElement(String uri, String localName, String qName, Attributes at) throws SAXException {     if(!qName.equals("tbook"))    {                DefaultMutableTreeNode newNode = new     DefaultMutableTreeNode(at.getValue("id"));                   root.add(newNode);                   root= newNode;/*Minh muốn dùng lại đoạn code này để truy vấn tìm thẻ có id = tên của node nhưng làm vậy thì lại sai trong quá trình tạo tree*/    }                 } public void endElement(String namespaceURI, String localName, String qName) throws SAXException {        root= (DefaultMutableTreeNode) root.getParent();                      }  public void startDocument() throws SAXException {        super.startDocument();          root= new DefaultMutableTreeNode ("Tiến còi");          ((DefaultTreeModel) tree.getModel()).setRoot(root);             } public void characters(char[] ch, int start, int length) throws SAXException {             s = new String(ch, start, length).trim();             } public void endDocument() throws SAXException {      model.reload();           }public void GuiTree() {                        /* Phưong thức này định nghĩa cây và add nó lên Jfame */                }}
    Cảm ơn mọi người nhiều.

  3. #3
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Cảm ơn anh nhiều.
    Em làm được rồi.
    P/s cái tài liệu anh đưa cũng cần tiếng anh. Không có chắc em chết. hihihi

 

 

Quyền viết bài

  • Bạn Không thể gửi Chủ đề mới
  • Bạn Không thể Gửi trả lời
  • Bạn Không thể Gửi file đính kèm
  • Bạn Không thể Sửa bài viết của mình
  •