如何将符合xml规范的String转化为XML文档中的element对象
如何将符合xml规范的String转化为XML文档中的element对象:
/** * 字符串转化为XML对象并加入到XML中的某一个节点下 * @throws DocumentException */public void stringToXml() throws DocumentException{SAXReader saxReader = new SAXReader();Document doc;try {doc = saxReader.read(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));if (doc!=null){ Element element=doc.getRootElement(); SAXReader saxReader1 = new SAXReader();Document document1 = saxReader1.read(fileName);Element element1 = (Element)document1.selectSingleNode("//template");element1.add(element);writeXML(document1); }} catch (UnsupportedEncodingException e) {e.printStackTrace();}}/** * 写XML * @param doc */private void writeXML(Document doc){ OutputFormat of = OutputFormat.createPrettyPrint(); of.setEncoding("utf-8"); FileOutputStream fos = null; XMLWriter xmlout = null; String lockfilename = fileName + ".lock"; MessageLock lock = new MessageLock(lockfilename); try{ if(lock.lock()) { fos = new FileOutputStream(this.fileName); xmlout = new XMLWriter(new OutputStreamWriter(fos, "utf-8"), of); xmlout.write(doc); xmlout.flush(); } }catch (Exception ex){ log.error("-->writeXml",ex); }finally{ lock.unlock(); if (fos != null){ try{ fos.close(); }catch (IOException ex1){ log.error("-->writeXml",ex1); } } if (xmlout != null){ try{ xmlout.close(); }catch (IOException ex2){ log.error("-->writeXml",ex2); } } } }
?