public ActionForward fetchEscalationLevel( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { EscalationDao escalationDaoImpl = new EscalationDaoImpl(); EscalationForm escalationForm = (EscalationForm) form; EscalationDTO escalationDTO = new EscalationDTO(); String escalation_level_status = null; Document document = DocumentHelper.createDocument(); Element root = document.addElement("options"); Element optionElement, hiddenElement; try { String escalation_type = escalationForm.getEscalation_type(); String workflow_step_id = escalationForm.getWorkflow_step_id(); System.out.println("escalation_type---->" + escalation_type); System.out.println("workflow_step_id---->" + workflow_step_id); if (escalation_type != null && workflow_step_id != null) { populate(form, request); List escalation_level_list = escalationDaoImpl.getEscalation_Level(escalation_type, workflow_step_id); if (escalation_level_list != null && escalation_level_list.size() > 0) { escalationForm.setEscalation_level_list(escalation_level_list); for (int intCounter = 0; intCounter < escalation_level_list.size(); intCounter++) { optionElement = root.addElement("option"); optionElement.addAttribute( "value", ((EscalationDTO) escalation_level_list.get(intCounter)).getEscalation_level()); optionElement.addAttribute( "text", ((EscalationDTO) escalation_level_list.get(intCounter)).getEscalation_level()); hiddenElement = root.addElement("hidden"); hiddenElement.addAttribute( "status", ((EscalationDTO) escalation_level_list.get(intCounter)) .getEscalation_level_status()); } } response.setContentType("text/xml"); response.setHeader("Cache-Control", "No-Cache"); PrintWriter out = response.getWriter(); XMLWriter writer = new XMLWriter(out); writer.write(document); logger.info("document : \n\n" + document.asXML()); writer.flush(); out.flush(); } } catch (Exception exception) { exception.printStackTrace(); } return null; }
/** 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(); } }
/** * 以字符串形式获取document * * @return * @throws IOException */ public String getMsg() throws IOException { XMLWriter xmlWriter = null; StringWriter writer = new StringWriter(); xmlWriter = new XMLWriter(writer); xmlWriter.write(doc); return writer.toString(); }
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(); } }
private void ajaxResponse(String htmlSource) { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8"); response.setHeader("Cache-control", "no-cache"); response.setHeader("pragma", "no-cache"); // 拿到一个输出的对象 PrintWriter out = null; try { out = response.getWriter(); // 格式化输出 OutputFormat oFormat = new OutputFormat(); oFormat.setEncoding("utf-8"); XMLWriter xmlWriter = new XMLWriter(out); xmlWriter.write(htmlSource); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { out.flush(); out.close(); } }
public static void main(String[] args) throws Exception { // 第一种方式 // 创建文档对象 /* * Document document = DocumentHelper.createDocument(); // 创建根元素节点 * Element root = DocumentHelper.createElement("student"); // 设置根元素节点 * document.setRootElement(root); */ Element root = DocumentHelper.createElement("student"); Document document = DocumentHelper.createDocument(root); // 元素添加属性 root.addAttribute("name", "张三"); // 添加子元素 Element helloElement = root.addElement("hello"); Element worldElement = root.addElement("world"); // 设置文本内容 helloElement.setText("hello"); worldElement.setText("world"); // 给hello设置一个属性 helloElement.addAttribute("age", "20"); // 输出到 XMLWriter xmlWriter = new XMLWriter(); xmlWriter.write(document); // 保存到xml文件中 XMLWriter xmlWriter1 = new XMLWriter(new FileOutputStream("t.xml"), new OutputFormat(" ", true)); xmlWriter1.write(document); }
/** * 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); } }
/** * 将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; } }
public STElement call() throws IOException { try { soapRequest.saveChanges(); if (debug) { System.out.print("********* REQUEST:"); Element e = new DOMReader().read(soapRequest.getSOAPPart()).getRootElement(); writer.write(e); System.out.println(); System.out.println("------------------"); } soapResponse = conn.call(soapRequest, wsdlURL); if (debug) { System.out.print("********* RESPONSE:"); Element e = new DOMReader().read(soapResponse.getSOAPPart()).getRootElement(); writer.write(e); System.out.println(); System.out.println("------------------"); } SOAPPart sp = soapResponse.getSOAPPart(); SOAPEnvelope env = sp.getEnvelope(); return new STElement(env.getBody()); } catch (SOAPException e) { e.printStackTrace(); return null; } }
// 修改:属性值,文本 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(); }
private void addXmlAnnotations(ModelAndView mav, String style) { List<ConceptAnnotation> annotations = (List<ConceptAnnotation>) mav.getModel().get("annotations"); mav.addObject("mimetype", "text/xml"); if (annotations != null) { Document doc = DocumentFactory.getInstance().createDocument(); Element mappings = doc.addElement("mappings"); for (ConceptAnnotation annotation : annotations) { Element mapping = mappings.addElement("mapping"); mapping.addAttribute("id", String.valueOf(annotation.getOid())); mapping.addAttribute("start", String.valueOf(annotation.getBegin())); mapping.addAttribute("end", String.valueOf(annotation.getEnd())); mapping.addAttribute("pname", annotation.getPname()); mapping.addAttribute("group", annotation.getStygroup()); mapping.addAttribute("codes", StringUtils.replace(annotation.getStycodes(), "\"", "")); mapping.setText(annotation.getCoveredText()); } OutputFormat outputFormat = "compact".equals(style) ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint(); StringWriter swriter = new StringWriter(); XMLWriter writer = new XMLWriter(swriter, outputFormat); try { writer.write(doc); writer.flush(); mav.addObject("stringAnnotations", swriter.toString()); } catch (IOException e) { logger.warn("IOException writing XML to buffer", e); } } }
/** * 格式化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; }
public HttpMethod toHttpMethod(DavContext ctxt, String targetUrl) throws IOException, DavException { if (ctxt.getUpload() != null && ctxt.getUpload().getSize() > 0) { PostMethod method = new PostMethod(targetUrl) { @Override public String getName() { return getMethodName(); } }; RequestEntity reqEntry; if (ctxt.hasRequestMessage()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(baos); writer.write(ctxt.getRequestMessage()); reqEntry = new ByteArrayRequestEntity(baos.toByteArray()); } else { // this could be a huge upload reqEntry = new InputStreamRequestEntity( ctxt.getUpload().getInputStream(), ctxt.getUpload().getSize()); } method.setRequestEntity(reqEntry); return method; } return new GetMethod(targetUrl) { @Override public String getName() { return getMethodName(); } }; }
/** * 修改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()); } }
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(); } }
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文件..."); }
@SuppressWarnings({"unchecked", "rawtypes"}) public static String executeXml( RepositoryFile file, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, IPentahoSession userSession) throws Exception { try { HttpSessionParameterProvider sessionParameters = new HttpSessionParameterProvider(userSession); HttpRequestParameterProvider requestParameters = new HttpRequestParameterProvider(httpServletRequest); Map parameterProviders = new HashMap(); parameterProviders.put("request", requestParameters); // $NON-NLS-1$ parameterProviders.put("session", sessionParameters); // $NON-NLS-1$ List messages = new ArrayList(); IParameterProvider requestParams = new HttpRequestParameterProvider(httpServletRequest); httpServletResponse.setContentType("text/xml"); // $NON-NLS-1$ httpServletResponse.setCharacterEncoding(LocaleHelper.getSystemEncoding()); boolean forcePrompt = "true" .equalsIgnoreCase( requestParams.getStringParameter( "prompt", "false")); // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ OutputStream contentStream = new ByteArrayOutputStream(); SimpleOutputHandler outputHandler = new SimpleOutputHandler(contentStream, false); IRuntimeContext runtime = null; try { runtime = executeInternal( file, requestParams, httpServletRequest, outputHandler, parameterProviders, userSession, forcePrompt, messages); Document responseDoc = SoapHelper.createSoapResponseDocument(runtime, outputHandler, contentStream, messages); OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); format.setEncoding("utf-8"); // $NON-NLS-1$ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(outputStream, format); writer.write(responseDoc); writer.flush(); return outputStream.toString("utf-8"); // $NON-NLS-1$ } finally { if (runtime != null) { runtime.dispose(); } } } catch (Exception e) { logger.warn( Messages.getInstance().getString("XactionUtil.XML_OUTPUT_NOT_SUPPORTED")); // $NON-NLS-1$ throw e; } }
/** * 修改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; }
private static void save(Document document, XMLWriter writer) throws IOException { try { writer.write(document); writer.flush(); } catch (UnsupportedEncodingException e) { throw new IOException(e.getMessage()); } }
/** * 通过XSD(XML Schema)校验XML * * @throws FileNotFoundException */ public boolean validateXMLByXSD(String testXSD, String xmlFileName) throws FileNotFoundException { // String xmlFileName = "Q:\\_dev_stu\\xsdtest\\src\\note.xml"; String xsdFileName = "E:/datashare/" + testXSD; FileInputStream fls = new FileInputStream(new File(xmlFileName)); try { // 创建默认的XML错误处理器 XMLErrorHandler errorHandler = new XMLErrorHandler(); // 获取基于 SAX 的解析器的实例 SAXParserFactory factory = SAXParserFactory.newInstance(); // 解析器在解析时验证 XML 内容。 factory.setValidating(true); // 指定由此代码生成的解析器将提供对 XML 名称空间的支持。 factory.setNamespaceAware(true); // 使用当前配置的工厂参数创建 SAXParser 的一个新实例。 SAXParser parser = factory.newSAXParser(); // 创建一个读取工具 SAXReader xmlReader = new SAXReader(); // 获取要校验xml文档实例 Document xmlDocument = (Document) xmlReader.read(fls); // 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 // [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。 parser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); parser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName); // 创建一个SAXValidator校验工具,并设置校验工具的属性 SAXValidator validator = new SAXValidator(parser.getXMLReader()); // 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。 validator.setErrorHandler(errorHandler); // 校验 validator.validate(xmlDocument); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); // 如果错误信息不为空,说明校验失败,打印错误信息 if (errorHandler.getErrors().hasContent()) { System.out.println("XML文件校验失败!"); writer.write(errorHandler.getErrors()); return false; } else { System.out.println("XML文件校验成功!"); return true; } } catch (Exception ex) { System.out.println( "XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage()); // ex.printStackTrace(); return false; } finally { try { fls.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * 保存文档 * * @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(); }
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(); } }
/** * Utility to serialize Document as a String for debugging * * @param document document * @return xml string * @throws IOException if error occurs */ private static String serialize(final Document document) throws IOException { final OutputFormat format = OutputFormat.createPrettyPrint(); final StringWriter sw = new StringWriter(); final XMLWriter writer = new XMLWriter(sw, format); writer.write(document); writer.flush(); sw.flush(); return sw.toString(); }
/** * 写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(); }
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()); }
@Override public void run() { try { writer.write(stub.document); writer.close(); generatedDocument = new String(documentOutputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } }
/** @param args */ public static void main(String[] args) throws Exception { SAXReader reader = new SAXReader(); Document doc = reader.read("tds.xml"); StringWriter sw = new StringWriter(); XMLWriter writer = new XMLWriter(sw, OutputFormat.createPrettyPrint()); writer.write(doc); System.out.println(sw.toString()); }
public String toString() { StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint()); try { writer.write(element); } catch (Exception e) { // Ignore. } return out.toString(); }
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(); }