码迷,mamicode.com
首页 > 编程语言 > 详细

java解析xml

时间:2016-03-12 13:10:43      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

<?xml version="1.0" encoding="UTF-8"?>
<mimetype>
    <default>
    <mime-type>text/html</mime-type>
    </default>
    <mime-mapping>
        <extension>zip</extension>
        <mime-type>application/zip</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>xml</extension>
        <mime-type>text/xml</mime-type>
    </mime-mapping>
</mimetype>                

1. SAXReader

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, DocumentException {
        //流式读取
        File file = new File("mimetype.xml");
        Document doc = new SAXReader().read(file);
        Element mimetype = doc.getRootElement();
        System.out.println("根元素名:" + mimetype.getName());
        Element defaultElement = mimetype.element("default");
        System.out.println("默认元素的mime-type:" + defaultElement.elementText("mime-type"));
        List<Element> mime_mappings = mimetype.elements("mime-mapping");
        System.out.println("元素集合的数据:" + mime_mappings.size());
    }

这是读文件的,好像直接读字符串还不怎么方便。

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><mimetype></mimetype>";
Reader reader = new StringReader(xml);
Document doc = new SAXReader().read(reader);

以Reader为桥梁来读取String类型的xml  2016-03-12 13:00:27

java解析xml

标签:

原文地址:http://www.cnblogs.com/angelshelter/p/5268404.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!