添加子節(jié)點出現問題
public?void?createXML(){ DocumentBuilder?db?=getDocumentBuilder(); Document?document=db.newDocument(); document.setXmlStandalone(true); Element?bookstore=document.createElement("bookStore"); //向bookstore根節(jié)點中添加子節(jié)點book Element?book=document.createElement("book"); Element?book2=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"); author.setTextContent("hhhh"); book.appendChild(year); Element?language=document.createElement("language"); author.setTextContent("English"); book.appendChild(language); //向book節(jié)點添加屬性 book.setAttribute("id",?"1"); book2.setAttribute("id",?"2"); //將book節(jié)點添加到bookstore根節(jié)點中 bookstore.appendChild(book); bookstore.appendChild(book2); //將bookstore節(jié)點(已經包含了book)添加到dom樹中 document.appendChild(bookstore); //創(chuàng)建TransformerFactory對象 TransformerFactory?tff=TransformerFactory.newInstance(); try?{ //創(chuàng)建Transformer對象 Transformer?tf=tff.newTransformer(); tf.setOutputProperty(OutputKeys.INDENT,?"yes"); tf.transform(new?DOMSource(document),?new?StreamResult(new?File("bookstore1.xml"))); }?catch?(TransformerConfigurationException?e)?{ //?TODO?自動生成的?catch?塊 e.printStackTrace(); } catch?(TransformerException?e)?{ //?TODO?自動生成的?catch?塊 e.printStackTrace(); } }
為什么我生成的XML文件不對 ?上邊代碼寫的不對嗎 ? 試了好幾遍都是下面這樣的結果
<?xml version="1.0" encoding="UTF-8"?><bookStore>
<book id="1">
<name>小王子</name>
<author>English</author>
<year/>
<language/>
</book>
<book id="2"/>
</bookStore>
2017-01-19
21,26行的?author.setTextContent(""); 是直接復制粘貼的吧,auther 沒改過來