protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ChessXMLService service = new ChessXMLServiceImpl(); String from = (String) request.getParameter("from"); String to = (String) request.getParameter("to"); ChessPlay play = new ChessPlay(); play.setColumnFrom(getColumnFrom(from)); play.setColumnTo(getColumnFrom(to)); play.setRowFrom(new Integer(getRowFrom(from))); play.setRowTo(new Integer(getRowFrom(to))); response.setContentType("text/xml"); Document doc = service.playWhite(play); Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream())); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(out, format); try { writer.write(doc); writer.close(); } catch (IOException e) { e.printStackTrace(); } finally { writer.close(); } }
/** * 修改xml某节点的值 * * @param inputXml 原xml文件 * @param nodes 要修改的节点 * @param attributename 属性名称 * @param value 新值 * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件 */ public static void modifyDocument( File inputXml, String nodes, String attributename, String value, String outXml) { try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(inputXml); List list = document.selectNodes(nodes); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attribute = (Attribute) iter.next(); if (attribute.getName().equals(attributename)) attribute.setValue(value); } XMLWriter output; if (outXml != null) { // 指定输出文件 output = new XMLWriter(new FileWriter(new File(outXml))); } else { // 输出文件为原文件 output = new XMLWriter(new FileWriter(inputXml)); } output.write(document); output.close(); } catch (DocumentException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } }
/** Saves the configuration on local drive. Usually you needn't to call this on your own. */ public void save() { Document xmlDocument = DocumentHelper.createDocument(); Element root = xmlDocument.addElement("config"); for (String id : config.keySet()) { Element tool = root.addElement("key"); tool.addAttribute("id", id); tool.addAttribute("value", config.get(id)); } try { OutputFormat format = OutputFormat.createPrettyPrint(); if (!Key.KEY_CONFIG_FILE.exists()) { Key.KEY_CONFIG_FILE.getParentFile().mkdirs(); Key.KEY_CONFIG_FILE.createNewFile(); } XMLWriter writer = new XMLWriter(new FileWriter(Key.KEY_CONFIG_FILE), format); writer.write(xmlDocument); writer.close(); } catch (IOException ex) { ex.printStackTrace(); } }
public static void main(String[] args) throws DocumentException { Document doc = DocumentHelper.createDocument(); Element ebank = doc.addElement("ebank"); Element gDecl = ebank.addElement("gDecl"); gDecl.setText(""); Element data = ebank.addElement("gTxData"); Element cHostCod = data.addElement("cHostCod"); cHostCod.setText("820001"); Element cRspCod = data.addElement("cRspCod"); cRspCod.setText("SC0000"); Element rescode = data.addElement("rescode"); rescode.setText("ISS0000"); Element resmsg = data.addElement("resmsg"); resmsg.setText("成功"); try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("GB2312"); XMLWriter writer = new XMLWriter(new FileOutputStream("src/output.xml"), format); writer.write(doc); writer.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("已成功创建XML文件..."); }
/** * 格式化xml * * @param xml * @return */ public static String formatXML(String xml) { SAXReader reader = null; XMLWriter writer = null; StringWriter stringWriter = null; try { reader = new SAXReader(); org.dom4j.Document document = reader.read(new StringReader(xml)); if (document != null) { stringWriter = new StringWriter(); OutputFormat format = new OutputFormat(" ", false); format.setSuppressDeclaration(true); writer = new XMLWriter(stringWriter, format); writer.write(document); writer.flush(); } return stringWriter.getBuffer().toString(); } catch (Exception e) { LOG.error("格式化xml失败", e); } finally { try { writer.close(); stringWriter.close(); } catch (Exception e) { // ignore } } return xml; }
/** * Write the report XML document out to file * * @param reportDir Directory to hold report file. */ public void save(File reportDir) throws BuildException { try { // Open the file matching the parameter suite final File file = new File(reportDir, FILENAME_PREFIX + suite + FILENAME_EXTENSION); // Retrieve the root element and adjust the failures and test attributes Element root = document.getRootElement(); root.addAttribute(FAILURE_ATTRIBUTE_LABEL, String.valueOf(suite.getFailures())); root.addAttribute(ERROR_ATTRIBUTE_LABEL, String.valueOf(suite.getErrors())); root.addAttribute(TESTS_ATTRIBUTE_LABEL, String.valueOf(suite.getTests())); root.addAttribute(IGNORE_ATTRIBUTE_LABEL, String.valueOf(suite.getSkips())); root.addAttribute(TIME_ATTRIBUTE_LABEL, String.valueOf(formatTime(suite.getTime()))); root.addAttribute(HOSTNAME_ATTRIBUTE_LABEL, getHostname()); final String timestamp = DateUtils.format(new Date(), DateUtils.ISO8601_DATETIME_PATTERN); root.addAttribute(TIMESTAMP_ATTRIBUTE_LABEL, timestamp); // Write the updated suite final OutputFormat format = OutputFormat.createPrettyPrint(); final XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); writer.write(document); writer.close(); } catch (Exception e) { throw new BuildException(ERROR_SAVING_REPORT, e); } }
public static void addToFlex(String name) { SAXReader reader = new SAXReader(); Document document; try { document = reader.read(new File(FLEX_CONFIG)); Element flex = document.getRootElement(); // Flex------------------------------------------------------------- Element destination = flex.addElement("destination"); destination.addAttribute("id", name); Element properties = destination.addElement("properties"); Element factory = properties.addElement("factory"); Element source = properties.addElement("source"); factory.addText("springFactory"); source.addText(Tools.firstLowcase(name)); // 更新保存---------------------------------------------------- XMLWriter writer = new XMLWriter(new FileWriter(FLEX_CONFIG)); writer.write(document); writer.close(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
// 修改:属性值,文本 public static void main(String[] args) throws Exception { Document doc = new SAXReader().read(new File("C:/Users/Administrator/Desktop/contact.xml")); // 方案一: 修改属性值 1.得到标签对象 2.得到属性对象 3.修改属性值 // 1.1 得到标签对象 Element contactElem = doc.getRootElement().element("contact"); // 1.2 得到属性对象 Attribute idAttr = contactElem.attribute("id"); // 1.3 修改属性值 idAttr.setValue("003"); // 方案二: 修改属性值 // 1.1 得到标签对象 Element contactElem1 = doc.getRootElement().element("contact"); // 1.2 通过增加同名属性的方法,修改属性值 contactElem.addAttribute("id", "004"); // 修改文本 1.得到标签对象 2.修改文本 Element nameElem = doc.getRootElement().element("contact").element("name"); nameElem.setText("demo7"); FileOutputStream out = new FileOutputStream("C:/Users/Administrator/Desktop/test/contact.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.close(); }
/** * 将document写入xml文件中 * * @param document * @param xmlFile * @return */ public boolean docToXmlFile(Document document, String xmlFile) { // 删除生成文件名中的中文字符 xmlFile = xmlFile.replaceAll("([\u4E00-\u9FA5]+)|([\u4E00-\u9FA5]+)", ""); try { // 排版缩进的格式 OutputFormat format = OutputFormat.createPrettyPrint(); // 设置编码,可按需设置 format.setEncoding("gb2312"); // 创建XMLWriter对象,指定了写出文件及编码格式 XMLWriter writer = new XMLWriter( new OutputStreamWriter(new FileOutputStream(new File(xmlFile)), "gb2312"), format); // 写入 writer.write(document); // 立即写入 writer.flush(); // 关闭操作 writer.close(); System.out.println("输出xml文件到:" + xmlFile); return true; } catch (IOException e) { e.printStackTrace(); return false; } }
/** * 修改XML文件中内容,并另存为一个新文件 重点掌握dom4j中如何添加节点,修改节点,删除节点 * * @param filename 修改对象文件 * @param newfilename 修改后另存为该文件 * @return 返回操作结果, 0表失败, 1表成功 */ public int modifyXMLFile(String filename, String newfilename) { int returnValue = 0; SAXReader saxReader = new SAXReader(); Document doc = null; try { /** 修改内容之一:如果book节点中show参数的内容为yes,则修改成no */ /** 先用xpath查找对象 */ doc = saxReader.read(new File(filename)); List list = doc.selectNodes("/books/book/@show"); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); if ("yes".equals(attr.getValue())) { attr.setValue("no"); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } /** 修改内容之二:把owner项内容改为Tshinghua 并在owner节点中加入date节点,date节点的内容为2004-09-11,还为date节点添加一个参数type */ List list = doc.selectNodes("/books/owner"); Iterator iter = list.iterator(); if (iter.hasNext()) { Element ownEle = (Element) iter.next(); ownEle.setText("Tshinghua"); Element dateEle = ownEle.addElement("date"); dateEle.setText("2012-12-17"); dateEle.addAttribute("type", "Gregorian calendar"); } /** 修改内容之三:若title内容为Dom4j Tutorials,则删除该节点 */ List list2 = doc.selectNodes("/books/book"); Iterator iter2 = list2.iterator(); while (iter2.hasNext()) { Element bookEle = (Element) iter2.next(); Iterator iterator = bookEle.elementIterator("title"); while (iterator.hasNext()) { Element titleElement = (Element) iterator.next(); if (titleElement.getText().equals("Dom4j Tutorials")) { bookEle.remove(titleElement); } } } try { /** 将document中的内容写入文件中 */ XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename))); writer.write(doc); writer.close(); /** 执行成功,需返回1 */ returnValue = 1; } catch (Exception ex) { ex.printStackTrace(); } return returnValue; }
public static void addToSRCSpring( BaseTable tmp, String daopath, String servicepath, String actionpath) { SAXReader reader = new SAXReader(); String name = tmp.getClass().getSimpleName(); Document document; try { document = reader.read(new File(SRC_SPRING_CONFIG)); Element beans = document.getRootElement(); beans.addComment( "===================以下是" + name + tmp.getComment() + "相关的beans===================="); // DAO------------------------------------------------------------- if (!daopath.equals("")) { Element dao = beans.addElement("bean"); dao.addAttribute("id", Tools.firstLowcase(name + "DAO")); dao.addAttribute("class", daopath); dao.addAttribute("parent", "DAO"); } // Server---------------------------------------------------------- if (!servicepath.equals("")) { Element service = beans.addElement("bean"); service.addAttribute("id", Tools.firstLowcase(name + "Service")); service.addAttribute("class", servicepath); service.addAttribute("parent", "BaseService"); Element serProperty = service.addElement("property"); serProperty.addAttribute("name", "dao"); serProperty.addAttribute("ref", Tools.firstLowcase(name + "DAO")); } // action---------------------------------------------------------- if (!actionpath.equals("")) { Element action = beans.addElement("bean"); action.addAttribute("name", name); action.addAttribute("class", actionpath); Element actionProperty = action.addElement("property"); actionProperty.addAttribute("name", name.toLowerCase() + "Service"); actionProperty.addAttribute("ref", name + "Server"); } // action---------------------------------------------------------- // Element action = beans.addElement("bean"); // action.addAttribute("name", name); // action.addAttribute("class", "com.zb.template." + name + "Action"); // Element actionProperty = action.addElement("property"); // actionProperty.addAttribute("name", name.toLowerCase() + "Service"); // actionProperty.addAttribute("ref", name + "Server"); // 更新保存---------------------------------------------------- XMLWriter writer = new XMLWriter(new FileWriter(SRC_SPRING_CONFIG)); writer.write(document); writer.close(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 写dom文档 * * @throws IOException */ public static void saveDocument(Document doc, FileWriter writer) throws IOException { // 输出全部原始数据,在编译器中显示 OutputFormat format = OutputFormat.createPrettyPrint(); format.setIndent(" "); format.setEncoding("UTF-8"); // 根据需要设置编码 XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(doc); xmlWriter.close(); }
/** * 保存文档 * * @param doc * @param xmlPath * @param encoding * @throws Exception */ public static void save(Document doc, String xmlPath, String encoding) throws Exception { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath), encoding), format); writer.write(doc); writer.flush(); writer.close(); }
@Override public void run() { try { writer.write(stub.document); writer.close(); generatedDocument = new String(documentOutputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } }
public void getXMLWrite(Document document, String filePath) throws Exception { OutputFormat of = new OutputFormat(" ", true); of.setEncoding("UTF-8"); XMLWriter xw = new XMLWriter(new FileWriter(filePath), of); xw.setEscapeText(false); xw.write(document); xw.close(); System.out.println(document.asXML()); }
public static void write2Xml(Document document) throws IOException { // 漂亮的格式输出器,设置格式输出为UTF-8 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(filepath), format); writer.write(document); writer.close(); }
protected static String toString(Document doc) { StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint()); try { xmlWriter.write(doc); xmlWriter.close(); } catch (IOException e) { throw new WinRMRuntimeIOException("Cannnot convert XML to String ", e); } return stringWriter.toString(); }
/** * 将document 对象写入指定的文件 * * @param xml * @param fileName */ public static void dumpToFile(Node xml, String fileName) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("GBK"); try { XMLWriter writer = new XMLWriter(new FileWriter(fileName), format); writer.write(xml); writer.close(); } catch (IOException e) { log.error("将document 对象写入指定的文件时出现IO错误 !", e); } }
/** * convert document to string * * @param document * @return XML as String * @throws java.io.IOException */ public static String convertDocumentToString(Document document) throws IOException { StringWriter sw = new StringWriter(); XMLWriter writer = new XMLWriter(sw); try { writer.write(document); writer.flush(); return sw.toString(); } finally { sw.close(); writer.close(); } }
public void stringXMLToFile(String filePath, String content) { try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(filePath), format); Document doc = DocumentHelper.parseText(content); xmlWriter.write(doc); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * xml转换为字符串 * * @param doc * @param encoding * @return * @throws Exception */ public static String toString(Document doc, String encoding) throws Exception { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); ByteArrayOutputStream byteOS = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS, encoding), format); writer.write(doc); writer.flush(); writer.close(); writer = null; return byteOS.toString(encoding); }
public static void writXml(Document document) { try { FileOutputStream fos = new FileOutputStream("D:\\a.xml"); OutputFormat of = new OutputFormat(" ", true); XMLWriter xw = new XMLWriter(fos, of); xw.write(document); xw.close(); } catch (IOException e) { System.out.println(e.getMessage()); } }
// Logs a new entry in the library RSS file public static synchronized void addRSSEntry( String title, String link, String description, File rssFile) { // File rssFile=new File("nofile.xml"); try { System.out.println("Looking for RSS file: " + rssFile.getCanonicalPath()); if (rssFile.exists()) { SAXReader reader = new SAXReader(); Document document = reader.read(rssFile); Element root = document.getRootElement(); Element channel = root.element("channel"); List items = channel.elements("item"); int numItems = items.size(); items = null; if (numItems > 9) { Element removeThisItem = channel.element("item"); channel.remove(removeThisItem); } Element newItem = channel.addElement("item"); Element newTitle = newItem.addElement("title"); Element newLink = newItem.addElement("link"); Element newDescription = newItem.addElement("description"); newTitle.setText(title); newDescription.setText(description); newLink.setText(link); Element pubDate = channel.element("pubDate"); pubDate.setText((new java.util.Date()).toString()); // now save changes FileWriter mywriter = new FileWriter(rssFile); OutputFormat format = OutputFormat.createPrettyPrint(); format.setLineSeparator(System.getProperty("line.separator")); XMLWriter writer = new XMLWriter(mywriter, format); writer.write(document); writer.close(); } } catch (IOException ioe) { System.out.println("ERROR: Could not find the RSS file."); ioe.printStackTrace(); } catch (DocumentException de) { System.out.println("ERROR: Could not read the RSS file."); de.printStackTrace(); } catch (Exception e) { System.out.println("Unknown exception trying to add an entry to the RSS file."); e.printStackTrace(); } }
/** * 设置系统设置 * * @param setting 系统设置 */ public static void set(Setting setting) { try { File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile(); Document document = new SAXReader().read(shopxxXmlFile); List<Element> elements = document.selectNodes("/shopxx/setting"); for (Element element : elements) { try { String name = element.attributeValue("name"); String value = beanUtils.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); fileOutputStream = new FileOutputStream(shopxxXmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } IOUtils.closeQuietly(fileOutputStream); } Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } catch (Exception e) { e.printStackTrace(); } }
/** * @param fileName 文件名 * @throws Exception 异常 */ private static void writeBack(String fileName) throws IOException, Exception { Document doc = getDocument(fileName); if (doc == null) { return; } OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter( new FileWriter( new File(XmlCfgUtil.class.getClassLoader().getResource(fileName + ".xml").toURI())), format); writer.write(doc); writer.close(); cfgMap.remove(fileName); }
public void saveDocument(Document document, File outputXml) { try { // 美化格式 OutputFormat format = OutputFormat.createPrettyPrint(); /*// 缩减格式 OutputFormat format = OutputFormat.createCompactFormat();*/ /*// 指定XML编码 format.setEncoding("GBK");*/ XMLWriter output = new XMLWriter(new FileWriter(outputXml), format); output.write(document); output.close(); } catch (IOException e) { System.out.println(e.getMessage()); } }
/** * 保存xml文件; * * @param document xml文件流; * @param filePath 文件存储的全路径(包括文件名) * @code 储存的编码; */ public void saveXmlFile(Document document, String filePath, String code) { if (document == null) { return; } XMLWriter output; try { OutputFormat format = new OutputFormat(); format.setEncoding(code); output = new XMLWriter(new FileWriter(new File(filePath)), format); output.write(document); output.close(); } catch (IOException e) { e.printStackTrace(); } }
private void writeResponse(Document sInsJson) throws PureException { try { response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1 response.setHeader("Pragma", "no-cache"); // HTTP 1.0 response.setDateHeader("Expires", -1); response.setDateHeader("max-age", 0); response.setContentType("text/xml"); response.setCharacterEncoding("utf-8"); XMLWriter writer = new XMLWriter(response.getWriter()); writer.write(sInsJson); writer.close(); } catch (IOException e) { throw new PureException(PureException.FILE_WRITE_FAILED, "failed to write response", e); } }
public String getQLDs() { OutputFormat prettyFormat = new OutputFormat(" ", true, "UTF-8"); StringWriter qldWriter = new StringWriter(); XMLWriter writer = new XMLWriter(qldWriter, prettyFormat); try { writer.write(doc); } catch (Exception e) { } finally { try { writer.close(); } catch (IOException e) { } } return qldWriter.toString(); }
/** * @方法功能描述:生成空的xml文件头 @方法名:createEmptyXmlFile * * @param xmlPath @返回类型:Document */ public static Document createEmptyXmlFile(String xmlPath) { if (xmlPath == null || xmlPath.equals("")) return null; XMLWriter output; Document document = DocumentHelper.createDocument(); OutputFormat format = OutputFormat.createPrettyPrint(); try { output = new XMLWriter(new FileWriter(xmlPath), format); output.write(document); output.close(); } catch (IOException e) { return null; } return document; }