首先,构造一个document对象:
Document doc = null; try { doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e) { e.printstacktrace(); return null; }然后,在doc中加入需要的节点,例如:
Element register = doc.createElement("Register"); register.setAttribute("id",REGISTER_ATTRIB_ID); register.setAttribute("type",REGISTER_ATTRIB_TYPE); doc.appendChild(register); Element params = doc.createElement("Params"); register.appendChild(params); Element item = doc.createElement(tagName); item.appendChild(doc.createTextNode(textNode)); params.appendChild(item);最后,将document对象转换成字符串 :
public static String convertDocToString(Document doc,String propertyName,String progertyValue){ Transformer transformer = null; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e) { e.printstacktrace(); return null; } catch (TransformerFactoryConfigurationError e) { e.printstacktrace(); return null; } transformer.setoutputProperty(propertyName,progertyValue); DOMSource domSource = new DOMSource(doc); StreamResult streamResult = new StreamResult(); ByteArrayOutputStream os = new ByteArrayOutputStream(); streamResult.setoutputStream(os); try { transformer.transform(domSource,streamResult); } catch (TransformerException e) { e.printstacktrace(); return null; } finally { try { os.flush(); os.close(); } catch (Exception e2) { e2.printstacktrace(); } } return os.toString(); }
原文地址:https://www.jb51.cc/xml/297094.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。