public void createXML(){
DocumentBuilder db=getDocumentBuilder();
Document document=db.newDocument();
document.setXmlStandalone(true);
Map<String, List<Element>> elementMap=new HashMap<String,List<Element>>();
List<Element> elementList=new ArrayList<Element>();
String[] nodeName=new String[]{"book","name","author","year","price","language"};
Map<String,List<String>> textMap=new HashMap<String,List<String>>();
textMap.put("name", Arrays.asList("冰与火之歌","安徒生童话"));
textMap.put("author", Arrays.asList("乔治马丁",null));
textMap.put("year", Arrays.asList("2016","2015"));
textMap.put("price", Arrays.asList("100","50"));
textMap.put("language", Arrays.asList(null,"English"));
//创建一个根节点bookstore
Element bookStore = document.createElement("bookstore");
//往bookstore根节点中添加子节点
for(int k=0;k<nodeName.length;k++){
elementList.clear();
for(int i=0;i<2;i++){
Element node=document.createElement(nodeName[k]);
elementList.add(node);
}
elementMap.put(nodeName[k], elementList);
}
for(int j=0;j<2;j++){
for(int i=1;i<nodeName.length;i++){
if(textMap.get(nodeName[i]).get(j)!=null){
elementMap.get(nodeName[i]).get(j).setTextContent(textMap.get(nodeName[i]).get(j));
elementMap.get(nodeName[0]).get(j).appendChild(elementMap.get(nodeName[i]).get(j));
}
}
elementMap.get(nodeName[0]).get(j).setAttribute("id", ((Integer)(j+1)).toString());
bookStore.appendChild(elementMap.get(nodeName[0]).get(j));
}
document.appendChild(bookStore);
TransformerFactory tff = TransformerFactory.newInstance();//工厂类,不能用new
try {
Transformer tf = tff.newTransformer();
//提供合理的换行
tf.setOutputProperty(OutputKeys.INDENT, "yes");
//StreamResult DOM中提供的输出流
tf.transform(new DOMSource(document), new StreamResult("bookstore1.xml"));
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 主方法,程序的入口
* @param args
*/
public static void main(String[] args) {
DOMTest domTest=new DOMTest();
domTest.createXML();
}
}
Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: 尝试在不允许的位置插入节点。
at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(ParentNode.java:380)
at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(ParentNode.java:288)
at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:237)
at dom.DOMTest.createXML(DOMTest.java:59)
at dom.DOMTest.main(DOMTest.java:29)