亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

XML之JDOM方式讀寫文件

標簽:
Java
1、JDOM解析XML文件
    private void parseXML() throws Exception {
        SAXBuilder saxBuilder = new SAXBuilder();//创建SAXBuilder对象
        FileInputStream in = new FileInputStream("books.xml");//创建输入流
        Document document = saxBuilder.build(in);//加载xml文件
        Element rootElement = document.getRootElement();//获取根节点
        List<Element> bookList = rootElement.getChildren();//获取子节点

        for(Element book:bookList){
            Book bookEntity = new Book();
            System.out.println("===开始解析第"+(bookList.indexOf(book)+1)+"本书===");
            //如果知道属性名为id,获取属性值则是 book.getAttributeValue("id");
            //首先解析属性,在不知道属性名称及个数的情况下,用getAttributes(),返回集合类型
            List<Attribute> attrList = book.getAttributes();
            for(Attribute attr:attrList){
                String attrName = attr.getName();
                String attrValue = attr.getValue(); //会自动去掉空格和换行,保留实际值
                System.out.println("属性名:"+attrName+"  属性值:"+attrValue);
            }
            //获取节点的子节点
            List<Element> bookChilds = book.getChildren();
            for(Element child:bookChilds){
                System.out.println("子节点名:"+child.getName()+"  子节点值:"+child.getValue());
                System.out.println("===结束解析第"+(bookList.indexOf(book)+1)+"本书===");
            System.out.println();
        }
    }
2、JDOM生成XML文件
    private void createXML() throws Exception{
        //生成根节点
        Element rss = new Element("rss");
        rss.setAttribute("version", "2.0");
        //创建Document对象
        Document document = new Document(rss);
        Element channel = new Element("channel");
        rss.addContent(channel);
        Element title = new Element("title");
        //title.setText("国内新闻");
        title.addContent(new CDATA("<国内最新新闻>"));//这样子可以处理特殊字符
        channel.addContent(title);
        //生成XML文档
        Format format = Format.getCompactFormat();
        format.setEncoding("GBK");//设置编码
        format.setIndent("");//设置换一行
        XMLOutputter outputer = new XMLOutputter(format);
        outputer.output(document, new FileOutputStream(new File("rss.xml")));
    }
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
軟件工程師
手記
粉絲
36
獲贊與收藏
349

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消