Java Code Examples for org.dom4j.io.OutputFormat

The following are top voted examples for showing how to use org.dom4j.io.OutputFormat. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: nest-old   File: HibernatePersistentConfigurationInitializer.java   Source Code and License 7 votes vote down vote up
/**
 * convert definition to hibernate xml
 * 
 * @param descriptor
 * @return
 * @throws IOException
 */
protected String convertToXML(IStandalonePersistentBeanDescriptor descriptor) {
	Document doc = createDocument(descriptor);

	StringWriter sw = new StringWriter();
	XMLWriter writer = new XMLWriter(sw, OutputFormat.createCompactFormat());
	try {
		writer.write(doc);
	} catch (IOException e) {
		if (getLogger().isErrorEnabled()) {
			getLogger().error("Failed to cast xml document to string.", e);
		}
		throw new ResourceException("Failed to cast xml document to string.", e);
	}
	if (getLogger().isDebugEnabled()) {
		getLogger()
				.debug("Class [" + descriptor.getResourceClass().getName()
						+ "] has been configured into hibernate. XML as [" + sw.toString().replace("\n", "") + "].");
	}
	return sw.toString();
}
 
Example 2
Project: alfresco-repository   File: ImportFileUpdater.java   Source Code and License 6 votes vote down vote up
/**
 * Get the writer for the import file
 * 
 * @param destination	the destination XML import file
 * @return				the XML writer
 */
private XMLWriter getWriter(String destination)
{
	try
	{
		 // Define output format
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setNewLineAfterDeclaration(false);
        format.setIndentSize(INDENT_SIZE);
        format.setEncoding(this.fileEncoding);

        return new XMLWriter(new FileOutputStream(destination), format);
	}
       catch (Exception exception)
       {
       	throw new AlfrescoRuntimeException("Unable to create XML writer.", exception);
       }
}
 
Example 3
Project: alfresco-repository   File: XMLTransferDestinationReportWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Start the transfer report
 */
public void startTransferReport(String encoding, Writer writer)
{
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding(encoding);
    
    try 
    {
    
    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();
    
    this.writer.startPrefixMapping(PREFIX, TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI);

    // Start Transfer Manifest  // uri, name, prefix
    this.writer.startElement(TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI, TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT,  PREFIX + ":" + TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT, EMPTY_ATTRIBUTES);
    
    } 
    catch (SAXException se)
    {
        se.printStackTrace();
    }
}
 
Example 4
Project: alfresco-repository   File: XMLTransferManifestWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Start the transfer manifest
 */
public void startTransferManifest(Writer writer) throws SAXException
{
    format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();

    this.writer.startPrefixMapping(PREFIX, TransferModel.TRANSFER_MODEL_1_0_URI);
    this.writer.startPrefixMapping("cm", NamespaceService.CONTENT_MODEL_1_0_URI);

    // Start Transfer Manifest // uri, name, prefix
    this.writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI,
                ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, PREFIX + ":"
                            + ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, EMPTY_ATTRIBUTES);
}
 
Example 5
Project: alfresco-repository   File: XMLTransferReportWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Start the transfer report
 */
public void startTransferReport(String encoding, Writer writer) throws SAXException
{
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding(encoding);
    
    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();
    
    this.writer.startPrefixMapping(PREFIX, TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI);

    // Start Transfer Manifest  // uri, name, prefix
    this.writer.startElement(TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI, TransferReportModel.LOCALNAME_TRANSFER_REPORT,  PREFIX + ":" + TransferReportModel.LOCALNAME_TRANSFER_REPORT, EMPTY_ATTRIBUTES);
}
 
Example 6
Project: joai-project   File: NCS_ITEMToNSDL_DCFormatConverter.java   Source Code and License 6 votes vote down vote up
/**
 *  Performs XML conversion from ADN to oai_dc format. Characters are encoded as UTF-8.
 *
 * @param  xml        XML input in the 'adn' format.
 * @param  docReader  A lucene doc reader for this record.
 * @param  context    The servlet context where this is running.
 * @return            XML in the converted 'oai_dc' format.
 */
public String convertXML(String xml, XMLDocReader docReader, ServletContext context) {
	getXFormFilesAndIndex(context);
	try {
					
		Transformer transformer = XSLTransformer.getTransformer(transform_file.getAbsolutePath());
		String transformed_content = XSLTransformer.transformString(xml, transformer);
		
		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Dom4j automatically writes using UTF-8, unless otherwise specified.
		OutputFormat format = OutputFormat.createPrettyPrint();
		StringWriter outputWriter = new StringWriter();
		XMLWriter writer = new XMLWriter(outputWriter, format);
		writer.write(document);
		outputWriter.close();
		writer.close();
		return outputWriter.toString();			
	} catch (Throwable e) {
		System.err.println("NCS_ITEMToNSDL_DCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 7
Project: joai-project   File: Dom4jUtils.java   Source Code and License 6 votes vote down vote up
/**
 *  Formats an {@link org.dom4j.Node} as a printable string
 *
 * @param  node  the Node to display
 * @return       a nicley-formatted String representation of the Node.
 */
public static String prettyPrint(Node node) {
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();

	format.setXHTML(true);
	//Default is false, this produces XHTML
	HTMLWriter ppWriter = new HTMLWriter(sw, format);
	try {
		ppWriter.write(node);
		ppWriter.flush();
	} catch (Exception e) {
		return ("Pretty Print Failed");
	}
	return sw.toString();
}
 
Example 8
Project: urule   File: FrameServletHandler.java   Source Code and License 6 votes vote down vote up
public void fileSource(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	String path=req.getParameter("path");
	path=Utils.decodeURL(path);
	InputStream inputStream=repositoryService.readFile(path,null);
	String content=IOUtils.toString(inputStream,"utf-8");
	inputStream.close();
	String xml=null;
	try{
		Document doc=DocumentHelper.parseText(content);
		OutputFormat format=OutputFormat.createPrettyPrint();
		StringWriter out=new StringWriter();
		XMLWriter writer=new XMLWriter(out, format);
		writer.write(doc);
		xml=out.toString();
	}catch(Exception ex){
		xml=content;
	}
	Map<String,Object> result=new HashMap<String,Object>();
	result.put("content", xml);
	writeObjectToJson(resp, result);
}
 
Example 9
Project: PackagePlugin   File: FileUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 删除配置
 *
 * @param name
 * @throws Exception
 */
public static void removeHttpConfig(String name) throws Exception {
    SAXReader reader = new SAXReader();
    File xml = new File(HTTP_CONFIG_FILE);
    Document doc;
    Element root;
    try (FileInputStream in = new FileInputStream(xml); Reader read = new InputStreamReader(in, "UTF-8")) {
        doc = reader.read(read);
        root = doc.getRootElement();
        Element cfg = (Element) root.selectSingleNode("/root/configs");
        Element e = (Element) root.selectSingleNode("/root/configs/config[@name='" + name + "']");
        if (e != null) {
            cfg.remove(e);
            CONFIG_MAP.remove(name);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(new FileOutputStream(xml), format);
        writer.write(doc);
        writer.close();
    }
}
 
Example 10
Project: unitimes   File: XmlApiHelper.java   Source Code and License 6 votes vote down vote up
@Override
public <R> void setResponse(R response) throws IOException {
	iResponse.setContentType("application/xml");
	iResponse.setCharacterEncoding("UTF-8");
	iResponse.setHeader("Pragma", "no-cache" );
	iResponse.addHeader("Cache-Control", "must-revalidate" );
	iResponse.addHeader("Cache-Control", "no-cache" );
	iResponse.addHeader("Cache-Control", "no-store" );
	iResponse.setDateHeader("Date", new Date().getTime());
	iResponse.setDateHeader("Expires", 0);
	iResponse.setHeader("Content-Disposition", "attachment; filename=\"response.xml\"" );
	Writer writer = iResponse.getWriter();
	try {
		new XMLWriter(writer, OutputFormat.createPrettyPrint()).write(response);
	} finally {
		writer.flush();
		writer.close();
	}
}
 
Example 11
Project: unitimes   File: AbstractSolver.java   Source Code and License 6 votes vote down vote up
@Override
public byte[] exportXml() throws IOException {
    Lock lock = currentSolution().getLock().readLock();
    lock.lock();
    try {
        boolean anonymize = ApplicationProperty.SolverXMLExportNames.isFalse();
        boolean idconv = ApplicationProperty.SolverXMLExportConvertIds.isTrue();

        ByteArrayOutputStream ret = new ByteArrayOutputStream();
        
        Document document = createCurrentSolutionBackup(anonymize, idconv);
        
        if (ApplicationProperty.SolverXMLExportConfiguration.isTrue())
        	saveProperties(document);
        
        (new XMLWriter(ret, OutputFormat.createPrettyPrint())).write(document);
        
        ret.flush(); ret.close();

        return ret.toByteArray();
    } finally {
    	lock.unlock();
    }
}
 
Example 12
Project: unitimes   File: BlobRoomAvailabilityService.java   Source Code and License 6 votes vote down vote up
protected void sendRequest(Document request) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        (new XMLWriter(writer,OutputFormat.createPrettyPrint())).write(request);
        writer.flush(); writer.close();
        SessionImplementor session = (SessionImplementor)new _RootDAO().getSession();
        Connection connection = session.getJdbcConnectionAccess().obtainConnection();
        try {
            CallableStatement call = connection.prepareCall(iRequestSql);
            call.setString(1, writer.getBuffer().toString());
            call.execute();
            call.close();
        } finally {
        	session.getJdbcConnectionAccess().releaseConnection(connection);
        }
    } catch (Exception e) {
        sLog.error("Unable to send request: "+e.getMessage(),e);
    } finally {
        _RootDAO.closeCurrentThreadSessions();
    }
}
 
Example 13
Project: gitplex-mit   File: VersionedDocument.java   Source Code and License 6 votes vote down vote up
public String toXML(boolean pretty) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	try {
		OutputFormat format = new OutputFormat();
		format.setEncoding(Charsets.UTF_8.name());
		if (pretty) {
			format.setIndent(true);
	        format.setNewlines(true);
		} else {
	        format.setIndent(false);
	        format.setNewlines(false);
		}
		new XMLWriter(baos, format).write(getWrapped());
		return baos.toString(Charsets.UTF_8.name());
	} catch (Exception e) {
		throw Throwables.propagate(e);
	}
}
 
Example 14
Project: minlia-iot   File: AbstractApiComponent.java   Source Code and License 6 votes vote down vote up
/**
 * 打印XML
 *
 * @param document
 */
protected void printXML(Document document) {
    if (log.isInfoEnabled()) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setExpandEmptyElements(true);
        format.setSuppressDeclaration(true);
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, format);
        try {
            writer.write(document);
            log.info(stringWriter.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 15
Project: lodsve-framework   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * xml 2 string
 *
 * @param document xml document
 * @return
 */
public static String parseXMLToString(Document document) {
    Assert.notNull(document);

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    StringWriter writer = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(writer, format);
    try {
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (IOException e) {
        throw new RuntimeException("XML解析发生错误");
    }
    return writer.toString();
}
 
Example 16
Project: sistra   File: InstanciaTelematicaProcessorEJB.java   Source Code and License 6 votes vote down vote up
/**
 * Devuelve la representaci�n de un Document XML en String bien formateado
 * y con codificaci�n UTF-8.
 * @param doc Documento.
 * @return string representando el documento formateado y en UTF-8.
 */
private String documentToString(Document doc) {
    String result = null;
    StringWriter writer = new StringWriter();
    OutputFormat of = OutputFormat.createPrettyPrint();
    of.setEncoding("UTF-8");
    XMLWriter xmlWriter = new XMLWriter(writer, of);
    try {
        xmlWriter.write(doc);
        xmlWriter.close();
        result = writer.toString();
    } catch (IOException e) {
        log.error("Error escribiendo xml", e);
    }
    return result;
}
 
Example 17
Project: codePay   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * doc2XmlFile
 * 将Document对象保存为一个xml文件到本地
 * @return true:保存成功  flase:失败
 * @param filename 保存的文件名
 * @param document 需要保存的document对象
 */
public static boolean doc2XmlFile(Document document,String filename)
{
   boolean flag = true;
   try{
         /* 将document中的内容写入文件中 */
         //默认为UTF-8格式,指定为"GB2312"
         OutputFormat format = OutputFormat.createPrettyPrint();
         format.setEncoding("GB2312");
         XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format);
         writer.write(document);
         writer.close();            
     }catch(Exception ex){
         flag = false;
         ex.printStackTrace();
     }
     return flag;      
}
 
Example 18
Project: dms-webapp   File: HttpClient.java   Source Code and License 6 votes vote down vote up
/**
 * 格式化XML
 * 
 * @param inputXML
 * @return
 * @throws Exception
 */
public static String formatXML(String inputXML) throws Exception {
	Document doc = DocumentHelper.parseText(inputXML);
	StringWriter out = null;
	if (doc != null) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			out = new StringWriter();
			XMLWriter writer = new XMLWriter(out, format);
			writer.write(doc);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}

		return out.toString();
	}

	return inputXML;
}
 
Example 19
Project: javacode-demo   File: Dom4jTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExpandEmptyElements() throws IOException {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("root");
    Element id = root.addElement("id");
    id.addText("1");

    root.addElement("empty");

    OutputFormat xmlFormat = new OutputFormat();
    // OutputFormat.createPrettyPrint();
    xmlFormat.setSuppressDeclaration(true);
    xmlFormat.setEncoding("UTF-8");
    // If this is true, elements without any child nodes
    // are output as <name></name> instead of <name/>.
    xmlFormat.setExpandEmptyElements(true);


    StringWriter out = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(out, xmlFormat);
    xmlWriter.write(document);
    xmlWriter.close();

    assertEquals("<root><id>1</id><empty></empty></root>", out.toString());
}
 
Example 20
Project: dls-repository-stack   File: NCS_ITEMToNSDL_DCFormatConverter.java   Source Code and License 6 votes vote down vote up
/**
 *  Performs XML conversion from ADN to oai_dc format. Characters are encoded as UTF-8.
 *
 * @param  xml        XML input in the 'adn' format.
 * @param  docReader  A lucene doc reader for this record.
 * @param  context    The servlet context where this is running.
 * @return            XML in the converted 'oai_dc' format.
 */
public String convertXML(String xml, XMLDocReader docReader, ServletContext context) {
	getXFormFilesAndIndex(context);
	try {
					
		Transformer transformer = XSLTransformer.getTransformer(transform_file.getAbsolutePath());
		String transformed_content = XSLTransformer.transformString(xml, transformer);
		
		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Dom4j automatically writes using UTF-8, unless otherwise specified.
		OutputFormat format = OutputFormat.createPrettyPrint();
		StringWriter outputWriter = new StringWriter();
		XMLWriter writer = new XMLWriter(outputWriter, format);
		writer.write(document);
		outputWriter.close();
		writer.close();
		return outputWriter.toString();			
	} catch (Throwable e) {
		System.err.println("NCS_ITEMToNSDL_DCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 21
Project: dls-repository-stack   File: Dom4jUtils.java   Source Code and License 6 votes vote down vote up
/**
 *  Formats an {@link org.dom4j.Node} as a printable string
 *
 * @param  node  the Node to display
 * @return       a nicley-formatted String representation of the Node.
 */
public static String prettyPrint(Node node) {
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();

	format.setXHTML(true);
	//Default is false, this produces XHTML
	HTMLWriter ppWriter = new HTMLWriter(sw, format);
	try {
		ppWriter.write(node);
		ppWriter.flush();
	} catch (Exception e) {
		return ("Pretty Print Failed");
	}
	return sw.toString();
}
 
Example 22
Project: bygle-ldp   File: XMLBuilder.java   Source Code and License 6 votes vote down vote up
public void testEscapeXML() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputFormat format = new OutputFormat(null, false, "ISO-8859-2");
    format.setSuppressDeclaration(true);

    XMLWriter writer = new XMLWriter(os, format);

    Document document = DocumentFactory.getInstance().createDocument();
    Element root = document.addElement("root");
    root.setText("bla &#c bla");

    writer.write(document);

    String result = os.toString();

    Document doc2 = DocumentHelper.parseText(result);
    doc2.normalize(); 
}
 
Example 23
Project: JCommons   File: BeanXMLWriter.java   Source Code and License 6 votes vote down vote up
public File write() throws Exception {
	Document doc = createDoc();

	// 读取文件
	FileOutputStream fos = new FileOutputStream(this.file);
	// 设置文件编码
	OutputFormat format = OutputFormat.createPrettyPrint();
	// 创建写文件方法
	org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(fos,
			format);
	// 写入文件

	xmlWriter.write(doc);
	// 关闭
	fos.close();
	xmlWriter.close();
	return this.file;
}
 
Example 24
Project: cernunnos   File: WriteDocumentTask.java   Source Code and License 6 votes vote down vote up
public void perform(TaskRequest req, TaskResponse res) {

		File f = new File((String) file.evaluate(req, res));
		if (f.getParentFile() != null) {
			// Make sure the necessary directories are in place...
			f.getParentFile().mkdirs();
		}
		
		try {
			XMLWriter writer = new XMLWriter(new FileOutputStream(f), OutputFormat.createPrettyPrint());
			writer.write((Node) node.evaluate(req, res));
		} catch (Throwable t) {
			String msg = "Unable to write the specified file:  " + f.getPath();
			throw new RuntimeException(msg, t);
		}
				
	}
 
Example 25
Project: ProteanBear_Java   File: XMLProcessor.java   Source Code and License 6 votes vote down vote up
/**方法(公共)<br>
* 名称:    save<br>
* 描述:    储存文档对象为本地文件(指定文档)<br>
* @param  doc - 指定文档
* @param  savePath - 储存路径
* @return boolean - 是否成功
*/public boolean save(Document doc,String savePath)
{
    boolean isSuccess=false;
    try
    {
        FileOutputStream output=new FileOutputStream(savePath);
        OutputFormat format=new OutputFormat("",true,"UTF-8");
        XMLWriter writer=new XMLWriter(output,format);
        writer.write(doc);
        writer.close();
        isSuccess=true;
    }
    catch(IOException ex)
    {
        isSuccess=false;
    }
    return isSuccess;
}
 
Example 26
Project: cpsolver   File: StudentRequestXml.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        ToolBox.configureLogging();
        StudentSectioningModel model = new StudentSectioningModel(new DataProperties());
        Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>();
        StudentSectioningXMLLoader xmlLoad = new StudentSectioningXMLLoader(model, assignment);
        xmlLoad.setInputFile(new File(args[0]));
        xmlLoad.load();
        Document document = exportModel(assignment, model);
        FileOutputStream fos = new FileOutputStream(new File(args[1]));
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 27
Project: CEC-Automatic-Annotation   File: WriteToXMLUtil.java   Source Code and License 6 votes vote down vote up
public static boolean writeToXML(Document document, String tempPath) {
	try {
		// 使用XMLWriter写入,可以控制格式,经过调试,发现这种方式会出现乱码,主要是因为Eclipse中xml文件和JFrame中文件编码不一致造成的
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding(EncodingUtil.CHARSET_UTF8);
		// format.setSuppressDeclaration(true);//这句话会压制xml文件的声明,如果为true,就不打印出声明语句
		format.setIndent(true);// 设置缩进
		format.setIndent("	");// 空行方式缩进
		format.setNewlines(true);// 设置换行
		XMLWriter writer = new XMLWriter(new FileWriterWithEncoding(new File(tempPath), EncodingUtil.CHARSET_UTF8), format);
		writer.write(document);
		writer.close();
	} catch (IOException e) {
		e.printStackTrace();
		MyLogger.logger.error("写入xml文件出错!");
		return false;
	}
	return true;
}
 
Example 28
Project: yalder   File: WikipediaCrawlTool.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the given xml document as nicely formated string.
 * 
 * @param node
 *            The xml document.
 * @return the formated xml as string.
 */
private static String formatXml(Node node) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndentSize(4);
    format.setTrimText(true);
    format.setExpandEmptyElements(true);
    
    StringWriter stringWriter = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
    try {
        xmlWriter.write(node);
        xmlWriter.flush();
    } catch (IOException e) {
        // this should never happen
        throw new RuntimeException(e);
    }

    return stringWriter.getBuffer().toString();
}
 
Example 29
Project: unitime   File: LowercaseTableNames.java   Source Code and License 6 votes vote down vote up
protected void write(String resource, Document document) throws IOException, DocumentException {
	File file = null;
	if (iSource == null) {
		file = new File(getClass().getClassLoader().getResource(resource).getFile());
	} else {
		file = new File(iSource + File.separator + resource);
	}
	info("  -- writing " + file + " ...");
	FileOutputStream fos = new FileOutputStream(file);
	try {
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setIndentSize(4);
		format.setPadText(false);
		new MyXMLWriter(fos, format).write(document);
	} finally {
		fos.flush(); fos.close();
	}
}
 
Example 30
Project: unitime   File: XmlApiHelper.java   Source Code and License 6 votes vote down vote up
@Override
public <R> void setResponse(R response) throws IOException {
	iResponse.setContentType("application/xml");
	iResponse.setCharacterEncoding("UTF-8");
	iResponse.setHeader("Pragma", "no-cache" );
	iResponse.addHeader("Cache-Control", "must-revalidate" );
	iResponse.addHeader("Cache-Control", "no-cache" );
	iResponse.addHeader("Cache-Control", "no-store" );
	iResponse.setDateHeader("Date", new Date().getTime());
	iResponse.setDateHeader("Expires", 0);
	iResponse.setHeader("Content-Disposition", "attachment; filename=\"response.xml\"" );
	Writer writer = iResponse.getWriter();
	try {
		new XMLWriter(writer, OutputFormat.createPrettyPrint()).write(response);
	} finally {
		writer.flush();
		writer.close();
	}
}
 
Example 31
Project: unitime   File: AbstractSolver.java   Source Code and License 6 votes vote down vote up
@Override
public byte[] exportXml() throws IOException {
    Lock lock = currentSolution().getLock().readLock();
    lock.lock();
    try {
        boolean anonymize = ApplicationProperty.SolverXMLExportNames.isFalse();
        boolean idconv = ApplicationProperty.SolverXMLExportConvertIds.isTrue();

        ByteArrayOutputStream ret = new ByteArrayOutputStream();
        
        Document document = createCurrentSolutionBackup(anonymize, idconv);
        
        if (ApplicationProperty.SolverXMLExportConfiguration.isTrue())
        	saveProperties(document);
        
        (new XMLWriter(ret, OutputFormat.createPrettyPrint())).write(document);
        
        ret.flush(); ret.close();

        return ret.toByteArray();
    } finally {
    	lock.unlock();
    }
}
 
Example 32
Project: unitime   File: BlobRoomAvailabilityService.java   Source Code and License 6 votes vote down vote up
protected void sendRequest(Document request) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        (new XMLWriter(writer,OutputFormat.createPrettyPrint())).write(request);
        writer.flush(); writer.close();
        SessionImplementor session = (SessionImplementor)new _RootDAO().getSession();
        Connection connection = session.getJdbcConnectionAccess().obtainConnection();
        try {
            CallableStatement call = connection.prepareCall(iRequestSql);
            call.setString(1, writer.getBuffer().toString());
            call.execute();
            call.close();
        } finally {
        	session.getJdbcConnectionAccess().releaseConnection(connection);
        }
    } catch (Exception e) {
        sLog.error("Unable to send request: "+e.getMessage(),e);
    } finally {
        _RootDAO.closeCurrentThreadSessions();
    }
}
 
Example 33
Project: unitime   File: BaseExport.java   Source Code and License 6 votes vote down vote up
public void saveXml(String fileName, Session session, Properties parameters) throws Exception {
    debug("Saving "+fileName);
    Document doc = saveXml(session, parameters);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(fileName);
        (new XMLWriter(fos,OutputFormat.createPrettyPrint())).write(doc);
        fos.flush();fos.close();fos=null;
    } finally {
        try {
            if (fos!=null) fos.close();
        } catch (IOException e) {
            fatal("Unable to write file "+fileName+", reason:"+e.getMessage(),e);
            throw e;
        }
    }
}
 
Example 34
Project: olat   File: FilePersister.java   Source Code and License 6 votes vote down vote up
/**
 * Persist results for this user/aiid as an XML document. dlPointer is aiid in this case.
 * 
 * @param doc
 * @param type
 * @param info
 */
public static void createResultsReporting(final Document doc, final Identity subj, final String type, final long aiid) {
    final File fUserdataRoot = new File(WebappHelper.getUserDataRoot());
    final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type;
    final File fReportingDir = new File(fUserdataRoot, path);
    try {
        fReportingDir.mkdirs();
        final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml"));
        final Element element = doc.getRootElement();
        final XMLWriter xw = new XMLWriter(os, new OutputFormat("  ", true));
        xw.write(element);
        // closing steams
        xw.close();
        os.close();
    } catch (final Exception e) {
        throw new OLATRuntimeException(FilePersister.class,
                "Error persisting results reporting for subject: '" + subj.getName() + "'; assessment id: '" + aiid + "'", e);
    }
}
 
Example 35
Project: olat   File: ContentPackage.java   Source Code and License 6 votes vote down vote up
/**
 * writes the manifest.xml
 */
void writeToFile() {
    final String filename = "imsmanifest.xml";
    final OutputFormat format = OutputFormat.createPrettyPrint();

    try {
        VFSLeaf outFile;
        // file may exist
        outFile = (VFSLeaf) cpcore.getRootDir().resolve("/" + filename);
        if (outFile == null) {
            // if not, create it
            outFile = cpcore.getRootDir().createChildLeaf("/" + filename);
        }
        final DefaultDocument manifestDocument = cpcore.buildDocument();
        final XMLWriter writer = new XMLWriter(outFile.getOutputStream(false), format);
        writer.write(manifestDocument);
    } catch (final Exception e) {
        log.error("imsmanifest for ores " + ores.getResourceableId() + "couldn't be written to file.", e);
        throw new OLATRuntimeException(CPOrganizations.class, "Error writing imsmanifest-file", new IOException());
    }
}
 
Example 36
Project: olat   File: QTIExportImportTest.java   Source Code and License 6 votes vote down vote up
private static QTIDocument exportAndImportToQTIFormat(QTIDocument qtiDocOrig) throws IOException {
    Document qtiXmlDoc = qtiDocOrig.getDocument();
    OutputFormat outformat = OutputFormat.createPrettyPrint();

    String fileName = qtiDocOrig.getAssessment().getTitle() + "QTIFormat.xml";
    OutputStreamWriter qtiXmlOutput = new OutputStreamWriter(new FileOutputStream(new File(TEMP_DIR, fileName)), Charset.forName("UTF-8"));
    XMLWriter writer = new XMLWriter(qtiXmlOutput, outformat);
    writer.write(qtiXmlDoc);
    writer.flush();
    writer.close();

    XMLParser xmlParser = new XMLParser(new IMSEntityResolver());
    Document doc = xmlParser.parse(new FileInputStream(new File(TEMP_DIR, fileName)), true);
    ParserManager parser = new ParserManager();
    QTIDocument qtiDocRestored = (QTIDocument) parser.parse(doc);
    return qtiDocRestored;
}
 
Example 37
Project: community-edition-old   File: ImportFileUpdater.java   Source Code and License 6 votes vote down vote up
/**
 * Get the writer for the import file
 * 
 * @param destination	the destination XML import file
 * @return				the XML writer
 */
private XMLWriter getWriter(String destination)
{
	try
	{
		 // Define output format
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setNewLineAfterDeclaration(false);
        format.setIndentSize(INDENT_SIZE);
        format.setEncoding(this.fileEncoding);

        return new XMLWriter(new FileOutputStream(destination), format);
	}
       catch (Exception exception)
       {
       	throw new AlfrescoRuntimeException("Unable to create XML writer.", exception);
       }
}
 
Example 38
Project: community-edition-old   File: XMLTransferDestinationReportWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Start the transfer report
 */
public void startTransferReport(String encoding, Writer writer)
{
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding(encoding);
    
    try 
    {
    
    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();
    
    this.writer.startPrefixMapping(PREFIX, TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI);

    // Start Transfer Manifest  // uri, name, prefix
    this.writer.startElement(TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI, TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT,  PREFIX + ":" + TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT, EMPTY_ATTRIBUTES);
    
    } 
    catch (SAXException se)
    {
        se.printStackTrace();
    }
}
 
Example 39
Project: community-edition-old   File: XMLTransferReportWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Start the transfer report
 */
public void startTransferReport(String encoding, Writer writer) throws SAXException
{
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding(encoding);
    
    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();
    
    this.writer.startPrefixMapping(PREFIX, TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI);

    // Start Transfer Manifest  // uri, name, prefix
    this.writer.startElement(TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI, TransferReportModel.LOCALNAME_TRANSFER_REPORT,  PREFIX + ":" + TransferReportModel.LOCALNAME_TRANSFER_REPORT, EMPTY_ATTRIBUTES);
}
 
Example 40
Project: snipsnap   File: XMLSnipExport.java   Source Code and License 6 votes vote down vote up
public static void store(OutputStream out, List snips, List users, String filter, List ignoreElements, File fileStore) {
  try {
    OutputFormat outputFormat = new OutputFormat();
    outputFormat.setEncoding("UTF-8");
    outputFormat.setNewlines(true);
    XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
    Element root = DocumentHelper.createElement("snipspace");
    xmlWriter.writeOpen(root);
    storeUsers(xmlWriter, users);
    storeSnips(xmlWriter, snips, filter, ignoreElements, fileStore);
    xmlWriter.writeClose(root);
    xmlWriter.flush();
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 41
Project: OLE-INST   File: JAXBContextFactory_UT.java   Source Code and License 6 votes vote down vote up
public static String prettyPrint(final String xml) {
    if (StringUtils.isBlank(xml)) {
        throw new RuntimeException("xml was null or blank in prettyPrint()");
    }

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    } catch (Exception e) {
        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
    }
    String[] xmlArray = StringUtils.split(sw.toString(), '\n');
    Object[] xmlContent = ArrayUtils.subarray(xmlArray, 1, xmlArray.length);
    StringBuilder xmlStr = new StringBuilder();
    for (Object object : xmlContent) {
        xmlStr.append(object.toString());
        xmlStr.append('\n');
    }
    return xmlStr.toString();
}
 
Example 42
Project: snipsnap   File: JDBCDatabaseExport.java   Source Code and License 6 votes vote down vote up
/**
   * Store snips and users from the SnipSpace to an xml document into a stream.
   * @param out outputstream to write to
   */
  public static void store(OutputStream out, String appOid, Connection connection) {
    try {
      OutputFormat outputFormat = new OutputFormat();
      outputFormat.setEncoding("UTF-8");
      outputFormat.setNewlines(true);

      XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
      xmlWriter.startDocument();
      Element root = DocumentHelper.createElement("snipspace");
      xmlWriter.writeOpen(root);

//      storeUsers(xmlWriter, connection);
      storeSnips(xmlWriter, appOid, connection);

      xmlWriter.writeClose(root);
      xmlWriter.endDocument();
      xmlWriter.flush();
      xmlWriter.close();
    } catch (Exception e) {
      System.err.println("JDBCDatabaseExport: error while writing document: " + e.getMessage());
    }
  }
 
Example 43
Project: Reer   File: DOM4JSerializer.java   Source Code and License 5 votes vote down vote up
public static void exportToFile(ExportInteraction exportInteraction, ExtensionFileFilter fileFilter, DOM4JSettingsNode settingsNode) {
    File file = promptForFile(exportInteraction, fileFilter);
    if (file == null) {
        //the user canceled.
        return;
    }

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        LOGGER.error("Could not write to file: " + file.getAbsolutePath(), e);
        exportInteraction.reportError("Could not write to file: " + file.getAbsolutePath());
        return;
    }

    try {
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint());
        Element rootElement = settingsNode.getElement();
        rootElement.detach();

        Document document = DocumentHelper.createDocument(rootElement);

        xmlWriter.write(document);
    } catch (Throwable t) {
        LOGGER.error("Internal error. Failed to save.", t);
        exportInteraction.reportError("Internal error. Failed to save.");
    } finally {
        closeQuietly(fileOutputStream);
    }
}
 
Example 44
Project: pndao   File: DaoGenHelper.java   Source Code and License 5 votes vote down vote up
public String mixMethodToData(DaoGen daoGen, String namespace, Map<String, MapperMethod> methodMap, String data) {
    if (data.isEmpty())
        data = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                "\n" +
                "<!DOCTYPE mapper\n" +
                "PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "\n" +
                "<mapper namespace=\"" + namespace + "\">\n" +
                "</mapper>\n";
    try {
        Document document = parseText(data);
        Element element = document.getRootElement();
        element.elements().forEach(sqlEle -> {
            String id = sqlEle.attribute("id").getText();
            methodMap.remove(id);
        });
        methodMap.forEach(getGenFunc(daoGen, element));

        OutputFormat format = OutputFormat.createPrettyPrint();
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            XMLWriter writer = new XMLWriter(outputStream, format);
            writer.write(document);
            writer.flush();

            return outputStream.toString("UTF-8");
        }
    } catch (DocumentException | IOException | SAXException e) {
        throw new Error(e);
    }
}
 
Example 45
Project: cucumber-framework-java   File: ModifyXML.java   Source Code and License 5 votes vote down vote up
public static String getPrettyXML(String xml) throws DocumentException, IOException {
    try {
        Document doc = DocumentHelper.parseText(xml);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);
        return sw.toString();
    } catch (DocumentException | IOException e) {
        throw new DocumentException("XML cannot be converted to pretty. XML Response : \n" + xml, e);
    }
}
 
Example 46
Project: alfresco-repository   File: PermissionModel.java   Source Code and License 5 votes vote down vote up
private InputStream processModelDocType(InputStream is, String dtdSchemaUrl) throws DocumentException, IOException
{
    SAXReader reader = new SAXReader();
    // read document without validation
    Document doc = reader.read(is);
    DocumentType docType = doc.getDocType();
    if (docType != null)
    {
        // replace DOCTYPE setting the full path to the xsd
        docType.setSystemID(dtdSchemaUrl);
    }
    else
    {
        // add the DOCTYPE
        docType = new DefaultDocumentType(doc.getRootElement().getName(), dtdSchemaUrl);
        doc.setDocType(docType);
    }

    ByteArrayOutputStream fos = new ByteArrayOutputStream();
    try
    {
        OutputFormat format = OutputFormat.createPrettyPrint(); // uses UTF-8
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        writer.flush();
    }
    finally
    {
        fos.close();
    }
    
    return new ByteArrayInputStream(fos.toByteArray());
}
 
Example 47
Project: alfresco-repository   File: XMLTransferRequsiteWriter.java   Source Code and License 5 votes vote down vote up
public XMLTransferRequsiteWriter(Writer out)
{
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    this.writer = new XMLWriter(out, format);
}
 
Example 48
Project: alfresco-repository   File: XMLWriter.java   Source Code and License 5 votes vote down vote up
public XMLWriter(OutputStream outputStream, boolean prettyPrint, String encoding)
        throws UnsupportedEncodingException
{
    OutputFormat format = prettyPrint ? OutputFormat.createPrettyPrint() : OutputFormat.createCompactFormat();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding(encoding);
    output = outputStream;
    this.dom4jWriter = new org.dom4j.io.XMLWriter(outputStream, format);
}
 
Example 49
Project: alfresco-repository   File: ExportSourceImporter.java   Source Code and License 5 votes vote down vote up
private XMLWriter createXMLExporter(Writer writer)
{
    // Define output format
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    // Construct an XML Exporter

    XMLWriter xmlWriter = new XMLWriter(writer, format);
    return xmlWriter;
}
 
Example 50
Project: ats-framework   File: XmlText.java   Source Code and License 5 votes vote down vote up
@Override
@PublicAtsApi
public String toString() {

    try {
        return getFormattedString(OutputFormat.createCompactFormat());
    } catch (XMLException e) {
        log.error(e.getMessage(), e.getCause());
        return "";
    }
}
 
Example 51
Project: ats-framework   File: XmlText.java   Source Code and License 5 votes vote down vote up
/**
 * @return the XML as nicely formatted text
 */
@PublicAtsApi
public String toFormattedString() {

    try {
        return getFormattedString(OutputFormat.createPrettyPrint());
    } catch (XMLException e) {
        log.error(e.getMessage(), e.getCause());
        return "";
    }

}
 
Example 52
Project: joai-project   File: OAISetsXMLConfigManager.java   Source Code and License 5 votes vote down vote up
/**
 *  Removes the given OAI set definition from the ListSets config XML file and writes it to disc.
 *
 * @param  setsConfigFile  The ListSets config file
 * @param  setSpec         The set to remove
 * @return                 True if the set existed and was removed
 * @exception  Exception   If error
 */
public static boolean removeOAISetSpecDefinition(File setsConfigFile, String setSpec) throws Exception {
	Document document = null;
	if (setsConfigFile == null || !setsConfigFile.exists())
		return false;

	// Create the XML DOM
	if (setsConfigFile.exists()) {
		SAXReader reader = new SAXReader();
		document = reader.read(setsConfigFile);
	}

	Element root = document.getRootElement();
	if (!root.getName().equals("ListSets"))
		throw new Exception("OAI Sets XML is incorrect. Root node is not 'ListSets'");

	// Remove the previous set definition, if present
	String xPath = "set[setSpec=\"" + setSpec + "\"]";
	Element prevSet = (Element) root.selectSingleNode(xPath);
	if (prevSet == null)
		return false;
	root.remove(prevSet);

	// Write the XML to disc
	OutputFormat format = OutputFormat.createPrettyPrint();
	XMLWriter writer = new XMLWriter(new FileWriter(setsConfigFile), format);
	writer.write(document);
	writer.close();

	return true;
}
 
Example 53
Project: joai-project   File: ADNToNSDLDCFormatConverter.java   Source Code and License 5 votes vote down vote up
/**
 *  Performs XML conversion from ADN to nsdl_dc format. Characters are encoded as UTF-8.
 *
 * @param  xml        XML input in the 'adn' format.
 * @param  context    The context in which this is running.
 * @param  docReader  Lucene DocReader for the item.
 * @return            XML in the converted 'nsdl_dc' format.
 */
public String convertXML(String xml, XMLDocReader docReader, ServletContext context) {
	getXFormFilesAndIndex(context);
	try {
		Transformer adn_to_nsdl_transformer = XSLTransformer.getTransformer(adn_to_nsdl_file.getAbsolutePath());
		Transformer namespace_out_transformer = XSLTransformer.getTransformer(namespace_out_file.getAbsolutePath());

		String transformed_content = XSLTransformer.transformString(xml, adn_to_nsdl_transformer);
		transformed_content = XSLTransformer.transformString(transformed_content, namespace_out_transformer);

		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Replace IDs with URL in each field as appropriate
		for (int i = 0; i < fieldsToReplace.length; i++)
			handleRelationField("//nsdl_dc:nsdl_dc/" + fieldsToReplace[i], document);

		// Dom4j automatically writes using UTF-8, unless otherwise specified.
		OutputFormat format = OutputFormat.createPrettyPrint();
		StringWriter outputWriter = new StringWriter();
		XMLWriter writer = new XMLWriter(outputWriter, format);
		writer.write(document);
		outputWriter.close();
		writer.close();
		return outputWriter.toString();
	} catch (Throwable e) {
		System.err.println("ADNToNSDLDCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 54
Project: joai-project   File: SchemaViewerForm.java   Source Code and License 5 votes vote down vote up
/**
 *  Description of the Method
 *
 *@param  node           Description of the Parameter
 *@return                Description of the Return Value
 *@exception  Exception  Description of the Exception
 */
private String prettyPrint(Node node)
	throws Exception {
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();
	//These are the default formats from createPrettyPrint, so you needn't set them:
	//  format.setNewlines(true);
	//  format.setTrimText(true);
	format.setXHTML(true);
	//Default is false, this produces XHTML
	HTMLWriter ppWriter = new HTMLWriter(sw, format);
	ppWriter.write(node);
	ppWriter.flush();
	return sw.toString();
}
 
Example 55
Project: joai-project   File: ADNToOAIDCFormatConverter.java   Source Code and License 5 votes vote down vote up
/**
 *  Performs XML conversion from ADN to oai_dc format. Characters are encoded as UTF-8.
 *
 * @param  xml        XML input in the 'adn' format.
 * @param  docReader  A lucene doc reader for this record.
 * @param  context    The servlet context where this is running.
 * @return            XML in the converted 'oai_dc' format.
 */
public String convertXML(String xml, XMLDocReader docReader, ServletContext context) {
	getXFormFilesAndIndex(context);
	try {
		Transformer adn_to_oai_transformer = XSLTransformer.getTransformer(adn_to_oai_file.getAbsolutePath());
		Transformer namespace_out_transformer = XSLTransformer.getTransformer(namespace_out_file.getAbsolutePath());

		String transformed_content = XSLTransformer.transformString(xml, adn_to_oai_transformer);
		transformed_content = XSLTransformer.transformString(transformed_content, namespace_out_transformer);
					
		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Replace IDs in the relation field only
		handleRelationField("//oai_dc:dc/dc:relation",document);
	
		// Dom4j automatically writes using UTF-8, unless otherwise specified.
		OutputFormat format = OutputFormat.createPrettyPrint();
		StringWriter outputWriter = new StringWriter();
		XMLWriter writer = new XMLWriter(outputWriter, format);
		writer.write(document);
		outputWriter.close();
		writer.close();
		return outputWriter.toString();			
	} catch (Throwable e) {
		System.err.println("ADNToOAIDCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 56
Project: urule   File: AbstractReferenceUpdater.java   Source Code and License 5 votes vote down vote up
protected String xmlToString(Document doc){
	StringWriter stringWriter = new StringWriter();
	OutputFormat xmlFormat = new OutputFormat();
	xmlFormat.setEncoding("UTF-8");
	XMLWriter xmlWriter = new XMLWriter(stringWriter, xmlFormat);
	try {
		xmlWriter.write(doc);
		xmlWriter.close();
		return stringWriter.toString();
	} catch (IOException e) {
		e.printStackTrace();
		throw new RuleException(e);
	}
}
 
Example 57
Project: TestDemo1-github   File: Dom4jHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 保存文档
 * @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();	
}
 
Example 58
Project: TestDemo1-github   File: Dom4jHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 59
Project: aaden-pay   File: LianlianBranchTest.java   Source Code and License 5 votes vote down vote up
private void writeXml(List<JSONArray> list) throws Exception {
	File file = new File(SAVE_PATH);
	if (file.exists())
		file.delete();

	// 生成一个文档
	Document document = DocumentHelper.createDocument();
	Element root = document.addElement("root");
	for (JSONArray jsonArray : list) {
		for (Object object : jsonArray) {
			JSONObject json = (JSONObject) object;
			System.out.println(json);
			Element element = root.addElement("branch");
			// 为cdr设置属性名和属性值
			element.addAttribute("branchId", json.getString("prcptcd").trim());// 支行行号
			element.addAttribute("bankCode", json.getString("bankCode").trim());// 银行类型
			element.addAttribute("cityCode", json.getString("cityCode").trim());// 城市代码
			element.addAttribute("branchName", json.getString("brabank_name").trim());// 支行名称
		}
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(SAVE_PATH)), "UTF-8"), format);
	// 写入新文件
	writer.write(document);
	writer.flush();
	writer.close();
}
 
Example 60
Project: lams   File: XMLHelper.java   Source Code and License 5 votes vote down vote up
public static void dump(Element element) {
	try {
		// try to "pretty print" it
		OutputFormat outFormat = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter( System.out, outFormat );
		writer.write( element );
		writer.flush();
		System.out.println( "" );
	}
	catch ( Throwable t ) {
		// otherwise, just dump it
		System.out.println( element.asXML() );
	}

}