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

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

DOM創建XML文本第二本書( 2-3 生成節點間的文本 作業)

標簽:
Java
public void createXML(){
        DocumentBuilder db = getDocumentBuilder();
        Document document = db.newDocument();
        document.setXmlStandalone(true);
        Element bookstore = document.createElement("bookStore");
        //向bookstore根节点中添加子节点book
        Element book = document.createElement("book");

        Element name = document.createElement("name");
        name.setTextContent("冰与火之歌");
        book.appendChild(name);
        Element author = document.createElement("author");
        author.setTextContent("乔治马丁");
        book.appendChild(author);
        Element year = document.createElement("year");
        year.setTextContent("2014");
        book.appendChild(year);
        Element price = document.createElement("price");
        price.setTextContent("99");
        book.appendChild(price);

        book.setAttribute("id", "1");
        //将book节点添加到bookstore节点中
        bookstore.appendChild(book);

        //向bookstore根节点中添加子节点book1
                Element book1 = document.createElement("book");

                Element name1 = document.createElement("name");
                name1.setTextContent("安徒生童话");
                book1.appendChild(name1);
                Element year1 = document.createElement("year");
                year1.setTextContent("2004");
                book1.appendChild(year1);
                Element price1 = document.createElement("price");
                price1.setTextContent("77");
                book1.appendChild(price1);
                Element language = document.createElement("language");
                language.setTextContent("English");
                book1.appendChild(language);            

                book1.setAttribute("id", "2");
                //将book节点添加到bookstore节点中
                bookstore.appendChild(book1);
                //将bookstore节点(已经包含了book)添加到dom树中
//              document.appendChild(bookstore);        
        //将bookstore节点(已经包含了book)添加到dom树中
        document.appendChild(bookstore);        
        //创建TransformerFactory对象
        TransformerFactory tff = TransformerFactory.newInstance();
        try {
            //创建Transformer对象
            Transformer tf = tff.newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.transform(new DOMSource(document), new StreamResult(new File("books1.xml")));            
        } catch (TransformerConfigurationException e) {         
            e.printStackTrace();
        }catch (TransformerException e) {           
            e.printStackTrace();
        }
    }

其它的教师上课都写了, COPY进去完美运行!book1内容是自己想出来的,还有好方法请各位指正!相互学习!!

點擊查看更多內容
1人點贊

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

評論

作者其他優質文章

正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

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

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

幫助反饋 APP下載

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

公眾號

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

舉報

0/150
提交
取消