package DOMTest;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class DOMtest001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
DOMtest001 d=new DOMtest001();
d.createXML();
}
public void createXML()
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db=dbf.newDocumentBuilder();
Document document= db.newDocument(); //生成新的document。
document.setXmlStandalone(true);
Element bookstore =document.createElement("bookstore");
Element book=document.createElement("book");
book.setAttribute("id", "1");
Element name=document.createElement("name");
name.setTextContent("小王子");
bookstore.appendChild(name);
//在bookstore节点中添加book节点 谁先添加 谁是另一个子节点。
bookstore.appendChild(book);
bookstore.appendChild(bookstore);//加根节点
TransformerFactory tff=TransformerFactory.newInstance();
try {
Transformer tf= tff.newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");//换行操作
try {
tf.transform(new DOMSource(document), new StreamResult(new File("book.xml")));
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*为什么运行后就报这个错误了?代码里面并没有报错
Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(ParentNode.java:375)
at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(ParentNode.java:284)
at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:235)
at DOMTest.DOMtest001.createXML(DOMtest001.java:42)
at DOMTest.DOMtest001.main(DOMtest001.java:24)*/