用java dom解析并生成一个新的xml

package com.lenovomobile.wap;

import com.lenovomobile.wap.domain.logic.WapFacade;
import com.lenovomobile.wap.help.Helper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: wangqiaowqo
 * Date: 2010-10-13
 * Time: 14:35:46
 * 该类的用途:.
 */
public class GenRSSnewsController implements Controller {

    private WapFacade wap;

    public void setWap(WapFacade wap) {
        this.wap = wap;
    }

    static String news = "http://data.3g.sina.com.cn/api/index.php?wm=9007_1002&cid=14";

    static String caijing = "http://data.3g.sina.com.cn/api/index.php?wm=9007_1002&cid=18";

    static String tiyu = "http://data.3g.sina.com.cn/api/index.php?wm=9007_1002&cid=17";

    static String yule = "http://data.3g.sina.com.cn/api/index.php?wm=9007_1002&cid=15";

    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {

        String id = request.getParameter("id");

        if (Helper.isNull(id)) {
            id = "news";
        }

        String RSSurl = news;

        if(id.equals("news")){
            RSSurl = news;
        }

        if(id.equals("caijing")){
            RSSurl = caijing;
        }

        if(id.equals("tiyu")){
            RSSurl = tiyu;
        }

        if(id.equals("yule")){
            RSSurl = yule;
        }

        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();

        ArrayList list = new ArrayList();

        //生成xml
        //以下为定义Document有关变量
        Document newdoc = null;
        Element newroot = null;
        DocumentBuilderFactory factory = null;
        DocumentBuilder builder = null;

        //以下为确定输出类型,定义输出变量
        response.setContentType("text/xml;charset=GB2312");

        try {

            URL url = new URL(RSSurl);
            URLConnection URLconnection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = httpConnection.getInputStream();
                BufferedReader is = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = is.readLine()) != null) {
                    buffer.append(line);
                }
                String str = buffer.toString();
                //String str = new String(buffer.toString().getBytes("ISO-8859-1"), "UTF-8");
                ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes("UTF-8"));
                in = stream;

                DocumentBuilder dombuilder = domfac.newDocumentBuilder();

                Document doc = dombuilder.parse(in);


                Element root = doc.getDocumentElement();
                NodeList nodes = root.getChildNodes();
                ArrayList newitems = new ArrayList();
                if (nodes != null) {
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Node channel = nodes.item(i);
                        if (channel.getNodeName().equals("channel")) {
                            NodeList items = channel.getChildNodes();

                            if (items != null) {
                                for (int j = 0; j < items.getLength(); j++) {
                                    Node item = items.item(j);
                                    if (item.getNodeName().equals("item")) {
                                        NodeList itemlist = item.getChildNodes();
                                        if (itemlist != null) {
                                            Item newitem = new Item();
                                            for (int k = 0; k < itemlist.getLength(); k++) {
                                                Node tmp = itemlist.item(k);
                                                if (tmp.getNodeName().equals("title")) {
                                                    newitem.setTitle(tmp.getTextContent());
                                                }
                                                if (tmp.getNodeName().equals("description")) {
                                                    newitem.setDexcription(tmp.getTextContent());
                                                }
                                            }
                                            if (newitem.getDexcription() != null && newitem.getTitle() != null) {
                                                newitems.add(newitem);
                                            }
                                        }

                                    }
                                }

                            }
                        }
                    }
                }

                list = newitems;
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
            factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();
            newdoc = builder.newDocument();
            newroot = newdoc.createElement("rss");
            newroot.setAttribute("version", "2.0");

            newdoc.appendChild(newroot);
            Element channel = newdoc.createElement("channel");
            newroot.appendChild(channel);

            for (int m = 0; m < list.size(); m ++) {
                Item newitem = (Item) list.get(m);
                Element item = newdoc.createElement("item");
                channel.appendChild(item);
                Element title = newdoc.createElement("title");
                item.appendChild(title);
                title.setTextContent(newitem.getTitle());
                Element description = newdoc.createElement("description");
                item.appendChild(description);
                description.setTextContent(newitem.getDexcription());
            }



        } catch (Exception e) {
            //out.println("出错提示:"+e.getMessage());
        }
        //PrintWriter out = response.getWriter();

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        DOMSource dom = new DOMSource(newdoc);
        StreamResult sr = new StreamResult(response.getOutputStream());
        t.setOutputProperty("encoding", "GB2312");
        //StringWriter sw=new StringWriter();
        //StreamResult sr=new StreamResult(sw);
        t.transform(dom, sr);

        //out.flush();
        //out.close();

        return null;
    }
}

class Item {
    private String title;

    private String dexcription;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDexcription() {
        return dexcription;
    }

    public void setDexcription(String dexcription) {
        this.dexcription = dexcription;
    }
}

你可能感兴趣的:(java,xml,PHP,servlet,WAP)