xml解析实例--新闻

前端之家收集整理的这篇文章主要介绍了xml解析实例--新闻前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. 效果
  2. 解析工具

Dom解析

public class NewsDom {
    public List<News> getNews(int page){
        List<News> newsList =new ArrayList<News>();
        try {
            File file = new File("news"+page+".xml");
            //因为已经生成,所以直接显示28日的新闻
            if(!file.exists()){
                URL url = new URL("http://api.avatardata.cn/GuoNeiNews/Query?key=c0342afffb154e659c0a58d4b470f4bb&page="+page+"&rows=10&dtype=xml");

                URLConnection con = url.openConnection();

                con.connect();

                InputStream is= con.getInputStream();

                OutputStream os = new FileOutputStream(file,true);

                byte[] bt= new byte[1024];
                int len = -1;
                while((len = is.read(bt))!=-1){
                    os.write(bt,0,len);
                }
                os.flush();
                os.close();
                is.close();

            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder Builder = factory.newDocumentBuilder();

            Document doc = Builder.parse(file);

            Element element = doc.getDocumentElement();

            //System.out.println(element);

            NodeList nodeList = doc.getElementsByTagName("NewsObj");

            int len=nodeList.getLength();
            for(int i=0;i<len;i++){
                News news = new News();
                int len2 = nodeList.item(i).getChildNodes().getLength();
                for(int j=0;j<len2;j++){
                    Node node1 = nodeList.item(i).getChildNodes().item(j);  
                    if(node1.getNodeType() ==1){
                        //1是元素节点
                        String content = node1.getFirstChild().getNodeValue();
                        String nodeName = node1.getNodeName();
                        if(content!=null&&!"".equals(content)){
                            if(nodeName.equals("ctime")){
                                news.setCtime(content);
                            }else if(nodeName.equals("description")){
                                news.setDescription(content);
                            }if(nodeName.equals("picUrl")){
                                news.setPicUrl(content);
                            }else if(nodeName.equals("url")){
                                news.setUrl(content);
                            }else if(nodeName.equals("title")){
                                news.setTitle(content);
                            }   
                        }

                    }

                }

                newsList.add(news);

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (DOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return newsList;
    }

    public List<News> getNews(File file){
        List<News> newsList =new ArrayList<News>();
        try {               

            if(!file.exists()){
                return null;
            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder Builder = factory.newDocumentBuilder();

            Document doc = Builder.parse(file);

            Element element = doc.getDocumentElement();         

            NodeList nodeList = doc.getElementsByTagName("NewsObj");

            int len=nodeList.getLength();
            for(int i=0;i<len;i++){
                News news = new News();
                int len2 = nodeList.item(i).getChildNodes().getLength();
                for(int j=0;j<len2;j++){
                    Node node1 = nodeList.item(i).getChildNodes().item(j);  
                    if(node1.getNodeType() ==1){
                        //1是元素节点
                        String content = node1.getFirstChild().getNodeValue();
                        String nodeName = node1.getNodeName();
                        if(content!=null&&!"".equals(content)){
                            if(nodeName.equals("ctime")){
                                news.setCtime(content);
                            }else if(nodeName.equals("description")){
                                news.setDescription(content);
                            }if(nodeName.equals("picUrl")){
                                news.setPicUrl(content);
                            }else if(nodeName.equals("url")){
                                news.setUrl(content);
                            }else if(nodeName.equals("title")){
                                news.setTitle(content);
                            }   
                        }

                    }

                }

                newsList.add(news);

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (DOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return newsList;
    }
  1. 主界面
public class mainView {

    protected Shell shell;
    private Table table;
    private Text filename;
    private Text text;
    private int page;
    private List<News> newsList;
    private TableColumn title;
    private TableItem news1;
    private TableItem news2;
    private TableItem news3;
    private TableItem news4;
    private TableItem news5;
    private TableItem news6;
    private TableItem news7;
    private TableItem news8;
    private TableItem news9;
    private TableItem news10;


    /** * Launch the application. * @param args */
    public static void main(String[] args) {
        try {
            mainView window = new mainView();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** * Open the window. */
    public void open() {
        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    /** * Create contents of the window. */
    protected void createContents() {
        shell = new Shell();
        shell.setSize(557,380);
        shell.setText("SWT Application");

        table = new Table(shell,SWT.BORDER | SWT.FULL_SELECTION);
        table.setBounds(10,10,410,240);
        table.setHeaderVisible(true);
        table.setLinesVisible(true);

        title = new TableColumn(table,SWT.NONE);
        title.setWidth(280);
        title.setText("新闻 标题");

        TableColumn frtime = new TableColumn(table,SWT.NONE);
        frtime.setWidth(126);
        frtime.setText("刷新事件");

        news1 = new TableItem(table,SWT.NONE);

        filename = new Text(shell,SWT.BORDER);
        filename.setBounds(437,123,73,23);
        filename.addKeyListener(new KeyListener() {

            @Override
            public void keyReleased(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyPressed(KeyEvent e) {
                if(filename.getText()!=null&&!"".equals(filename.getText())&&e.keyCode == 13){
                    File file = new File(filename.getText());
                    if(!file.exists()){
                        MessageBox mb = new MessageBox(shell);
                        mb.setMessage("文件不存在或文件错误");
                        mb.setText("error");
                        mb.open();
                    }else{
                        fresh(file);
                    }
                }

            }
        });

        Button bxml = new Button(shell,SWT.NONE);
        bxml.setBounds(437,170,80,27);
        bxml.setText("生成xml");

        Button changejson = new Button(shell,SWT.NONE);
        changejson.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                change();
            }
        });
        changejson.setBounds(437,211,27);
        changejson.setText("xml转为json");

        Label lblNewLabel = new Label(shell,SWT.NONE);
        lblNewLabel.setBounds(437,90,17);
        lblNewLabel.setText("请输入文件名\r\n");

        Button prevIoUs = new Button(shell,SWT.NONE);
        prevIoUs.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                if(page!=1){
                    page--;
                    text.setText(""+page);
                    fresh(page);
                }

            }
        });
        prevIoUs.setBounds(31,261,27);
        prevIoUs.setText("上一页");

        Button next = new Button(shell,SWT.NONE);
        next.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                page++;
                text.setText(""+page);
                fresh(page);
            }
        });
        next.setBounds(310,27);
        next.setText("下一页");

        Label lblNewLabel_1 = new Label(shell,SWT.NONE);
        lblNewLabel_1.setBounds(117,271,15,17);
        lblNewLabel_1.setText("第");

        text = new Text(shell,SWT.BORDER | SWT.READ_ONLY);
        text.setText("1");
        text.setBounds(138,265,28,23);
        page=Integer.parseInt(text.getText());

        Label lblNewLabel_2 = new Label(shell,SWT.NONE);
        lblNewLabel_2.setBounds(176,17);
        lblNewLabel_2.setText("页");

        Label lblNewLabel_3 = new Label(shell,SWT.NONE);
        lblNewLabel_3.setBounds(216,61,17);
        lblNewLabel_3.setText("每页十行");

        Label link = new Label(shell,SWT.NONE);
        link.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseDown(MouseEvent e) {
                int i=table.getSelectionIndex();
                System.out.println(i);
                String url = newsList.get(i).getUrl();
                /*try { Runtime.getRuntime().exec(url); } catch (IOException e1) { }*/

                if(java.awt.Desktop.isDesktopSupported()){
                    try {
                    //创建一个URI实例
                    java.net.URI uri = java.net.URI.create(url);
                    //获取当前系统桌面扩展
                    java.awt.Desktop dp = java.awt.Desktop.getDesktop();
                    //判断系统桌面是否支持要执行的功能
                    if(dp.isSupported(java.awt.Desktop.Action.BROWSE)){
                    //获取系统默认浏览器打开链接
                    dp.browse(uri);   
                    }
                    } catch(java.lang.NullPointerException e1){
                    //此为uri为空时抛出异常
                    } catch (java.io.IOException e1) {
                    //此为无法获取系统默认浏览器
                    }            
                }
            }
        });
        link.setBounds(31,317,17);
        link.setText("超链接地址");

        Label Golink = new Label(shell,SWT.NONE);
        Golink.setBounds(31,294,17);
        Golink.setText("Go超链接");


        news2 = new TableItem(table,SWT.NONE);

        news3 = new TableItem(table,SWT.NONE);

        news4 = new TableItem(table,SWT.NONE);

        news5 = new TableItem(table,SWT.NONE);

        news6 = new TableItem(table,SWT.NONE);

        news7 = new TableItem(table,SWT.NONE);

        news8 = new TableItem(table,SWT.NONE);

        news9 = new TableItem(table,SWT.NONE);

        news10 = new TableItem(table,SWT.NONE);

        fresh(page);


    }

    private void fresh(int i){
        NewsDom nd=new NewsDom();
        newsList =new ArrayList<News>();
        newsList=nd.getNews(i);         
        settext(newsList);
    }

    private void fresh(File file){
        NewsDom nd=new NewsDom();
        if(nd.getNews(file)!=null){
            newsList =new ArrayList<News>();            
            newsList=nd.getNews(file);          
            settext(newsList);
        }else{
            MessageBox mb = new MessageBox(shell);
            mb.setMessage("文件无效");
            mb.setText("error");
            mb.open();
        }

    }

    private void settext(List<News> newsList){
        news1.setText(new String[]{newsList.get(0).getTitle(),newsList.get(0).getCtime()});
        news2.setText(new String[]{newsList.get(1).getTitle(),newsList.get(1).getCtime()});
        news3.setText(new String[]{newsList.get(2).getTitle(),newsList.get(2).getCtime()});
        news4.setText(new String[]{newsList.get(3).getTitle(),newsList.get(3).getCtime()});
        news5.setText(new String[]{newsList.get(4).getTitle(),newsList.get(4).getCtime()});
        news6.setText(new String[]{newsList.get(5).getTitle(),newsList.get(5).getCtime()});
        news7.setText(new String[]{newsList.get(6).getTitle(),newsList.get(6).getCtime()});
        news8.setText(new String[]{newsList.get(7).getTitle(),newsList.get(7).getCtime()});
        news9.setText(new String[]{newsList.get(8).getTitle(),newsList.get(8).getCtime()});
        news10.setText(new String[]{newsList.get(9).getTitle(),newsList.get(9).getCtime()});
    }       

    private void change(){
        Xml2JsonUtil xju=new Xml2JsonUtil();
        File file = new File("news"+page+".xml");

        String json=xju.xml2JSON(file);
        Json js=new Json();
        js.open(json);
    }

}

猜你在找的XML相关文章