Java Code Examples for org.dom4j.io.XMLWriter

The following are top voted examples for showing how to use org.dom4j.io.XMLWriter. 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: formatter   File: FormatUtil.java   View source code 6 votes vote down vote up
/**
* 
* @Title: close 
* @Description: Close writer 
* @param @param w 
* @return void
* @throws
 */
public static void close(XMLWriter xw)
{
    if (null == xw)
    {
        return;
    }
    try
    {
        xw.close();
        xw = null;
    }
    catch(IOException e)
    {
        FormatView.getView().getStat().setText("Failed to close writer: " + e.getMessage());
    }
}
 
Example 2
Project: alfresco-repository   File: ImportFileUpdater.java   View source code 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: ImportFileUpdater.java   View source code 6 votes vote down vote up
public void doWork(XmlPullParser reader, XMLWriter writer)
	throws Exception
{
	// Deal with the contents of the tag
	int eventType = reader.getEventType();
	while (eventType != XmlPullParser.END_TAG) 
       {
		eventType = reader.next();
		if (eventType == XmlPullParser.START_TAG) 
		{
			ImportFileUpdater.this.outputCurrentElement(reader, writer, new OutputChildren());
		}
		else if (eventType == XmlPullParser.TEXT)
		{
			// Write the text to the output file
			writer.write(reader.getText());
		}
       }			
}
 
Example 4
Project: alfresco-repository   File: XMLTransferDestinationReportWriter.java   View source code 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 5
Project: alfresco-repository   File: XMLTransferManifestWriter.java   View source code 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 6
Project: alfresco-repository   File: XMLTransferReportWriter.java   View source code 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 7
Project: joai-project   File: NCS_ITEMToNSDL_DCFormatConverter.java   View source code 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 8
Project: joai-project   File: TransformTester.java   View source code 6 votes vote down vote up
public String transformString (String input, String transform, String tFactory) {
	try {
		File transform_file = new File (xsl_dir, transform);

		Transformer transformer = XSLTransformer.getTransformer(transform_file.getAbsolutePath(), tFactory);
		String transformed_content = XSLTransformer.transformString(input, transformer);
		
		prtln ("\ntransformer: " + transformer.getClass().getName());
		
		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 t) {
		prtln (t.getMessage());
		t.printStackTrace();
		return "";
	}
}
 
Example 9
Project: urule   File: FrameServletHandler.java   View source code 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 10
Project: PackagePlugin   File: FileUtil.java   View source code 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 11
Project: unitimes   File: XmlApiHelper.java   View source code 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 12
Project: unitimes   File: AbstractSolver.java   View source code 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 13
Project: unitimes   File: BlobRoomAvailabilityService.java   View source code 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 14
Project: gitplex-mit   File: VersionedDocument.java   View source code 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 15
Project: testing_platform   File: Tools.java   View source code 6 votes vote down vote up
public static void updateJmx(String jmxFilePath,String csvFilePath,String csvDataXpath) throws IOException, DocumentException {
    SAXReader reader = new SAXReader();
    Document documentNew =  reader.read(new File(jmxFilePath));
    List<Element> list = documentNew.selectNodes(csvDataXpath);
    if( list.size()>1 ){
        System.out.println("报错");
    }else{
        Element e = list.get(0);
        List<Element> eList = e.elements("stringProp");
        for(Element eStringProp:eList){
            if( "filename".equals( eStringProp.attributeValue("name") ) ){
                System.out.println("==========");
                System.out.println( eStringProp.getText() );
                eStringProp.setText(csvFilePath);
                break;
            }
        }
    }

    XMLWriter writer = new XMLWriter(new FileWriter(new File( jmxFilePath )));
    writer.write(documentNew);
    writer.close();

}
 
Example 16
Project: alfresco-remote-api   File: PropFindMethod.java   View source code 6 votes vote down vote up
/**
 * Output the supported lock types XML element
 * 
 * @param xml XMLWriter
 */
protected void writeLockTypes(XMLWriter xml)
{
    try
    {
        AttributesImpl nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_SUPPORTED_LOCK, WebDAV.XML_NS_SUPPORTED_LOCK, nullAttr);

        // Output exclusive lock
        // Shared locks are not supported, as they cannot be supported by the LockService (relevant to ALF-16449).
        writeLock(xml, WebDAV.XML_NS_EXCLUSIVE);

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_SUPPORTED_LOCK, WebDAV.XML_NS_SUPPORTED_LOCK);
    }
    catch (Exception ex)
    {
        throw new AlfrescoRuntimeException("XML write error", ex);
    }
}
 
Example 17
Project: alfresco-remote-api   File: PropPatchMethod.java   View source code 6 votes vote down vote up
/**
 * Generates the error tag
 * 
 * @param xml XMLWriter
 */
protected void generateError(XMLWriter xml)
{
    try
    {
        // Output the start of the error element
        Attributes nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR, nullAttr);
        // Output error
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_CANNOT_MODIFY_PROTECTED_PROPERTY));

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR);
    }
    catch (Exception ex)
    {
        // Convert to a runtime exception
        throw new AlfrescoRuntimeException("XML processing error", ex);
    }
}
 
Example 18
Project: minlia-iot   File: AbstractApiComponent.java   View source code 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 19
Project: lodsve-framework   File: XmlUtils.java   View source code 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 20
Project: sistra   File: InstanciaTelematicaProcessorEJB.java   View source code 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 21
Project: codePay   File: XmlUtil.java   View source code 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 22
Project: dms-webapp   File: HttpClient.java   View source code 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 23
Project: javacode-demo   File: Dom4jTest.java   View source code 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 24
Project: org.lovian.eaxmireader   File: FileHandler.java   View source code 6 votes vote down vote up
/**
 * Write the document based on DOM4J to the tmp file in disk
 * 
 * @param document
 *            document of SysML based on DOM4j
 * @throws IOException
 */
public static String writeTmpXmiFIle(Document document) throws IOException {
	String method = "FileHandler_writeTmpXmiFIle(): ";
	long startTime = System.currentTimeMillis();
	MyLog.info(method + "start");

	File fixedFile = FileHandler.createTempFileInOS(FIXED_FILE_NAME);
	String targetPath = fixedFile.getPath();

	XMLWriter writer = new XMLWriter(new FileWriter(targetPath));
	writer.write(document);
	writer.close();

	MyLog.info(method + "end with " + (System.currentTimeMillis() - startTime) + " millisecond");
	MyLog.info();
	
	return targetPath;
}
 
Example 25
Project: powermock-examples-maven   File: AbstractXMLRequestCreatorBase.java   View source code 6 votes vote down vote up
/**
 * Convert a dom4j xml document to a byte[].
 * 
 * @param document
 *            The document to convert.
 * @return A <code>byte[]</code> representation of the xml document.
 * @throws IOException
 *             If an exception occurs when converting the document.
 */
public byte[] convertDocumentToByteArray(Document document)
		throws IOException {
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	XMLWriter writer = new XMLWriter(stream);
	byte[] documentAsByteArray = null;
	try {
		writer.write(document);
	} finally {
		writer.close();
		stream.flush();
		stream.close();
	}
	documentAsByteArray = stream.toByteArray();
	return documentAsByteArray;
}
 
Example 26
Project: dls-repository-stack   File: NCS_ITEMToNSDL_DCFormatConverter.java   View source code 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 27
Project: dls-repository-stack   File: TransformTester.java   View source code 6 votes vote down vote up
public String transformString (String input, String transform, String tFactory) {
	try {
		File transform_file = new File (xsl_dir, transform);

		Transformer transformer = XSLTransformer.getTransformer(transform_file.getAbsolutePath(), tFactory);
		String transformed_content = XSLTransformer.transformString(input, transformer);
		prtln ("\ntransformer: " + transformer.getClass().getName());
		prtln ("tFactory: " + tFactory);
		
		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 t) {
		prtln (t.getMessage());
		t.printStackTrace();
		return "";
	}
}
 
Example 28
Project: bygle-ldp   File: XMLBuilder.java   View source code 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 29
Project: ApkCustomizationTool   File: Command.java   View source code 6 votes vote down vote up
/**
 * 修改strings.xml文件内容
 *
 * @param file    strings文件
 * @param strings 修改的值列表
 */
private void updateStrings(File file, List<Strings> strings) {
    try {
        if (strings == null || strings.isEmpty()) {
            return;
        }
        Document document = new SAXReader().read(file);
        List<Element> elements = document.getRootElement().elements();
        elements.forEach(element -> {
            final String name = element.attribute("name").getValue();
            strings.forEach(s -> {
                if (s.getName().equals(name)) {
                    element.setText(s.getValue());
                    callback("修改 strings.xml name='" + name + "' value='" + s.getValue() + "'");
                }
            });
        });
        XMLWriter writer = new XMLWriter(new FileOutputStream(file));
        writer.write(document);
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 30
Project: ApkCustomizationTool   File: Command.java   View source code 6 votes vote down vote up
/**
 * 修改bools.xml文件内容
 *
 * @param file  bools文件
 * @param bools 修改的值列表
 */
private void updateBools(File file, List<Bools> bools) {
    try {
        if (bools == null || bools.isEmpty()) {
            return;
        }
        Document document = new SAXReader().read(file);
        List<Element> elements = document.getRootElement().elements();
        elements.forEach(element -> {
            final String name = element.attribute("name").getValue();
            bools.forEach(s -> {
                if (s.getName().equals(name)) {
                    element.setText(s.getValue());
                    callback("修改 bools.xml name='" + name + "' value='" + s.getValue() + "'");
                }
            });
        });
        XMLWriter writer = new XMLWriter(new FileOutputStream(file));
        writer.write(document);
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 31
Project: powermock   File: AbstractXMLRequestCreatorBase.java   View source code 6 votes vote down vote up
/**
 * Convert a dom4j xml document to a byte[].
 * 
 * @param document
 *            The document to convert.
 * @return A <code>byte[]</code> representation of the xml document.
 * @throws IOException
 *             If an exception occurs when converting the document.
 */
public byte[] convertDocumentToByteArray(Document document)
		throws IOException {
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	XMLWriter writer = new XMLWriter(stream);
	byte[] documentAsByteArray = null;
	try {
		writer.write(document);
	} finally {
		writer.close();
		stream.flush();
		stream.close();
	}
	documentAsByteArray = stream.toByteArray();
	return documentAsByteArray;
}
 
Example 32
Project: cernunnos   File: WriteDocumentTask.java   View source code 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 33
Project: ProteanBear_Java   File: XMLProcessor.java   View source code 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 34
Project: cpsolver   File: StudentRequestXml.java   View source code 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 35
Project: Improve   File: HibernateUtil.java   View source code 6 votes vote down vote up
/**
 * 把hbm.xml的路径加入到cfg.xml的mapping结点
 *
 * @param cfg.xml的路径
 * @param hbm.xml的路径
 */
public static void updateHbmCfg(URL url,String hbm)
{
	try
	{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(url);
		Element element = (Element)doc.getRootElement()
		.selectSingleNode("session-factory");
		
		Element hbmnode = element.addElement("mapping");
		hbmnode.addAttribute("resource", hbm);
		String filepath = url.getFile();
		if (filepath.charAt(0)=='/')
			filepath = filepath.substring(1);
		FileOutputStream outputstream = new FileOutputStream(filepath);
		XMLWriter writer = new XMLWriter(outputstream);
		writer.write(doc);
		outputstream.close();
	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
}
 
Example 36
Project: CEC-Automatic-Annotation   File: WriteToXMLUtil.java   View source code 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 37
Project: yalder   File: WikipediaCrawlTool.java   View source code 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 38
Project: taskerbox   File: TaskerboxXmlReader.java   View source code 6 votes vote down vote up
private void handleMacrosNode(Element xmlChannel) throws IOException {

    for (Object attrObj : xmlChannel.elements()) {
      DefaultElement e = (DefaultElement) attrObj;

      StringWriter sw = new StringWriter();
      XMLWriter writer = new XMLWriter(sw);
      writer.write(e.elements());

      if (this.tasker.getMacros().containsKey(e.attributeValue("name"))) {
        throw new RuntimeException("Macro " + e.attributeValue("name") + " already exists in map.");
      }

      this.tasker.getMacros().put(e.attributeValue("name"), sw.toString());
      this.tasker.getMacroAttrs().put(e.attributeValue("name"), e.attributes());
    }

  }
 
Example 39
Project: unitime   File: XmlApiHelper.java   View source code 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 40
Project: unitime   File: AbstractSolver.java   View source code 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();
    }
}