处理XML的一般方法

来源:互联网 发布:淘宝网店卖商品收费吗 编辑:程序博客网 时间:2024/05/18 03:54

一般来说处理xml,采用jdom和dom4j这两种方式解析,这两种方式几乎是一样的,我曾经试了一次,把jdom的jar包移除,在导入dom4j的jar包,使用Eclipse自动修复功能导入,程序完全是可以运行的,可能是我接触到的解析方式都很基础的原因。

 

1.将输入流转换为String字符串

   // 把流转换为字符串    private String convertStreamToString(InputStream is) throws IOException {        BufferedReader reader = null;        StringBuilder builder = new StringBuilder();                   if(is == null){        return "";        }        String line = null;        try {        reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));            while ((line = reader.readLine()) != null) {            builder.append(line + "\n");            }        } catch (IOException e) {        throw e;        } finally {            try {            if(is != null){            is.close();            }            } catch (IOException e) {            throw e;            }        }           return builder.toString();    }


 

2.把String类型转换为Doucument类型

    //把字符串转化为xml document    private Document convertStringToDocument(String xmlString) throws DocumentException {    Document doc = null;    if(!xmlString.equals("")){    try {    doc = DocumentHelper.parseText(xmlString);    } catch (DocumentException e) {    throw e;    }     }    return doc;    }


 

 

原创粉丝点击