DOM创建XML文本第二本书( 2-3 生成节点间的文本 作业)

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内容是自己想出来的,还有好方法请各位指正!相互学习!!

点赞