如何利用JDOM创建xml文件
下面作者在一个新闻管理的项目中使用JDOM创建xml文件的例子。目的是通过JDOM产生用于数据交换的xml文件。
/** * 构造Mail XML,并将xml文件置于服务器中,供第三方邮件商发送 * * @param storyInfo 新闻内容对象 * @param mails 邮件列表 * @return * @throws IOException */ public static void build(StoryInfo storyInfo, String[] mails) { if (mails == null || mails.length == 0) { log.warn("WARNING", "NO EMAILS TO BE SENT!"); return; } Element element = buildElement(storyInfo, mails); Document doc = new Document(); doc.setContent(element); FileWriter writer; XMLOutputter ōutputter = new XMLOutputter(); try { String fileName = "/" + storyInfo.getStoryId() + ".xml"; writer = new FileWriter(Constant.FILE_DIR_TMEP + fileName); Format format = Format.getPrettyFormat(); format.setEncoding("GBK"); outputter.setFormat(format); outputter.output(doc, writer); writer.close(); log.info("FILE " + Constant.FILE_DIR_TMEP + fileName + " IS WRITEN."); CommonUtil.copy(Constant.FILE_DIR_TMEP + fileName, Constant.FILE_DIR_BK + fileName); CommonUtil.copy(Constant.FILE_DIR_TMEP + fileName, Constant.FILE_DIR + fileName); log.info("FILE " + fileName + "IS MOVED TO ." + Constant.FILE_DIR + fileName); log.info("" + mails.length + " MAILS SENT."); } catch (IOException e) { throw new FaxMailRuntimeException(e); } } /** * 构造整棵XML树的根节点 * * @param storyInfo * @param mails * @return */ public static Element buildElement(StoryInfo storyInfo, String[] mails) { // 主节点 Element story = new Element("story"); // 子节点 Element storyId = create("storyId", storyInfo.getStoryId()); Element storyNo = create("storyNo", storyInfo.getStoryNo()); Element sendFlag = create("sendFlag", Constant.DEFAULT_NO); Element sendDate = create("sendDate", storyInfo.getSendDate()); Element sendTime = create("sendTime", storyInfo.getSendTime()); Element headline = create("headline", getEnforcedTitle(storyInfo)); Element content = new Element("content"); CDATA contentCdata = new CDATA("contentCdata"); contentCdata.setText(buildConent(storyInfo)); content.addContent(contentCdata); Element emails = new Element("emails"); // 生成emails节点 for (int i = 0; i < mails.length; i++) { Element mail = new Element("email"); mail.setAttribute("value", mails[i]); mail.setAttribute("isSucceed", Constant.DEFAULT_STRING); mail.setAttribute("sendTime", Constant.DEFAULT_STRING); mail.setAttribute("error", Constant.DEFAULT_STRING); emails.addContent(mail); }