Java Code Examples for org.dom4j.Document#setXMLEncoding()

The following examples show how to use org.dom4j.Document#setXMLEncoding() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ComponentHelper.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
   * 导出一个元素
   * @param modelPath   pms/model/layout(docorator or portlet)的绝对路径
   * @param component        元素实体
   * @param eXMLFile    元素的XML文件名 "/decorator.xml"
   */
  public static void exportComponent(String modelPath, Component component, String eXMLFile) {
      String elementName = EasyUtils.toUtf8String(component.getName());
      String exportFileName = elementName + ".xml";;
      String outPath; // 导出zip或xml文件路径
      
      Document doc = XMLDocUtil.dataXml2Doc(component.getDefinition());
      doc.setXMLEncoding(System.getProperty("file.encoding"));
      
      String subpath = component.getCode();
File filePath = FileHelper.findPathByName(new File(modelPath), subpath);
      if ( filePath != null ) {
          // 如果在pms/model/layout(docorator or portlet)文件夹下有该导出的xml文件就覆盖该文件,并以zip的形式导出
          exportFileName = elementName + ".zip";
          
          // 写回原来的文件
          FileHelper.writeXMLDoc(doc, filePath + "/" + eXMLFile); 
          
          // 导出成zip文件,并获得zip文件的路径
          outPath = FileHelper.exportZip(modelPath, filePath); 
      }
      else {
          // 如果model/layout(docorator、portlet)文件夹下没有导出的xml文件,则先将文件内容写到一个临时xml文件,再导出该临时文件
          FileHelper.writeXMLDoc(doc, outPath = modelPath + "/" + System.currentTimeMillis() + ".xml");
      }
      
      downloadFileByHttp(outPath, exportFileName);
  }
 
Example 2
Source File: PublishUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * 生成单个文章发布文件
 * @param article 
 * @param publishPath
 * @return
 */
public static String publishOneArticle(Article article, String publishPath) {
       // 删除已发布的文章,如果有的话
       String pubUrl = article.getPubUrl();
       if(pubUrl != null) {
           new File(pubUrl).delete();
       }
       
	// 生成发布路径
	File publishDir = new File(publishPath);
	if (!publishDir.exists()) {
		publishDir.mkdirs();
	}
	
	Document doc = DocumentHelper.createDocument();
	doc.setXMLEncoding(ArticleHelper.getSystemEncoding()); //一般:windows “GBK” linux “UTF-8”
	Element articleNode = doc.addElement("Article");
	
       Map<String, Object> articleAttributes = article.getAttributes4XForm(); // 包含文章的所有属性
       articleAttributes.remove("content");
	addValue2XmlNode(articleNode, articleAttributes);
	
	Element contentNode = articleNode.addElement("content");
	contentNode.addCDATA(article.getContent());
       
	// 发布文章对文章附件的处理
	Element eleAtts = articleNode.addElement("Attachments");
       ArticleHelper.addPicListInfo(eleAtts, article.getAttachments());
       
       // 以 “栏目ID_文章ID.xml” 格式命名文章发布的xml文件
       String fileName = article.getChannel().getId() + "_" + article.getId() + ".xml";
	String filePathAndName = publishPath + "/" + fileName;
       FileHelper.writeXMLDoc(doc, filePathAndName);
	return filePathAndName;
}
 
Example 3
Source File: DataDstXml.java    From xresloader with MIT License 5 votes vote down vote up
/**
 * 转储常量数据
 * 
 * @return 常量数据,不支持的时候返回空
 */
public final byte[] dumpConst(HashMap<String, Object> data) throws ConvException, IOException {
    // pretty print
    OutputFormat of = null;
    if (ProgramOptions.getInstance().prettyIndent <= 0) {
        of = OutputFormat.createCompactFormat();
    } else {
        of = OutputFormat.createPrettyPrint();
        of.setIndentSize(ProgramOptions.getInstance().prettyIndent);
    }

    // build xml tree
    Document doc = DocumentHelper.createDocument();
    String encoding = SchemeConf.getInstance().getKey().getEncoding();
    if (null != encoding && false == encoding.isEmpty()) {
        doc.setXMLEncoding(encoding);
        of.setEncoding(encoding);
    }

    doc.setRootElement(DocumentHelper.createElement(ProgramOptions.getInstance().xmlRootName));
    doc.getRootElement().addComment("this file is generated by xresloader, please don't edit it.");

    writeData(doc.getRootElement(), data, "");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(bos, of);
    writer.write(doc);

    return bos.toByteArray();
}
 
Example 4
Source File: LoadConfigure.java    From krpc with MIT License 4 votes vote down vote up
/**
 * 加载该服务下的配置文件,并初始化相关内容
 *
 * @param serviceRootPath
 * @throws Exception
 */
public static void load(String serviceRootPath) throws Exception {

    String serviceLib = serviceRootPath + File.separator + "lib";
    String serviceConf = serviceRootPath + File.separator + "conf";

    // 读取该服务的配置文件
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File(serviceConf + File.separator + "service.xml"));
    document.setXMLEncoding("UTF-8");
    Element node = document.getRootElement();

    Element proNode = node.element("property");

    Element connectionNode = proNode.element("connection");
    Element nettyNode = proNode.element("netty");

    Global.getInstance().setMaxBuf(Integer.parseInt(nettyNode.attributeValue("maxBuf")));

    Global.getInstance().setIp(connectionNode.attributeValue("ip"));

    if (Global.getInstance().getPort() == null) {
        Global.getInstance().setPort(Integer.parseInt(connectionNode.attributeValue("port")));
    } else {
        connectionNode.setAttributeValue("port", String.valueOf(Global.getInstance().getPort()));
        FileOutputStream fos = new FileOutputStream(serviceConf + File.separator + "service.xml");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        OutputFormat of = new OutputFormat();
        of.setEncoding("UTF-8");
        XMLWriter write = new XMLWriter(osw, of);
        write.write(document);
        write.close();
    }


    Global.getInstance().setTimeout(Integer.parseInt(connectionNode.attributeValue("timeout")));

    Map<String, String> serviceMap = new HashMap<String, String>();
    Element servicesNode = node.element("services");

    List<Element> serviceList = servicesNode.elements("service");
    for (Element e : serviceList) {
        serviceMap.put(e.attributeValue("name"), e.attributeValue("impl"));
    }

    initService(serviceMap, serviceLib);

    /**
     * 从配置文件中获取注册中心zk的信息
     */
    Global.getInstance().setZookeeperInfo(ZookeeperInfo.createByElement(node));

}
 
Example 5
Source File: CommonDao.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 生成XML importFile 导出xml工具类
 */
public HttpServletResponse createXml(ImportFile importFile) {
	HttpServletResponse response = importFile.getResponse();
	HttpServletRequest request = importFile.getRequest();
	try {
		// 创建document对象
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		// 创建根节点
		String rootname = importFile.getEntityName() + "s";
		Element rElement = document.addElement(rootname);
		Class entityClass = importFile.getEntityClass();
		String[] fields = importFile.getField().split(",");
		// 得到导出对象的集合
		List objList = loadAll(entityClass);
		Class classType = entityClass.getClass();
		for (Object t : objList) {
			Element childElement = rElement.addElement(importFile.getEntityName());
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i];
				// 第一为实体的主键
				if (i == 0) {
					childElement.addAttribute(fieldName, String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				} else {
					Element name = childElement.addElement(fieldName);
					name.setText(String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				}
			}

		}
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		File fileWriter = new File(ctxPath + "/" + importFile.getFileName());
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(fileWriter));

		xmlWriter.write(document);
		xmlWriter.close();
		// 下载生成的XML文件
		UploadFile uploadFile = new UploadFile(request, response);
		uploadFile.setRealPath(importFile.getFileName());
		uploadFile.setTitleField(importFile.getFileName());
		uploadFile.setExtend("bak");
		viewOrDownloadFile(uploadFile);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return response;
}
 
Example 6
Source File: XmlExport.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
public static Document createDocument() {
	Document document = DocumentHelper.createDocument();
	document.setXMLEncoding(UTF_8.name());
	document.addComment(XmlExport.FILE_COMMENT);
	return document;
}
 
Example 7
Source File: DataDstXml.java    From xresloader with MIT License 4 votes vote down vote up
@Override
public final byte[] build(DataDstImpl compiler) throws ConvException {
    // pretty print
    OutputFormat of = null;
    if (ProgramOptions.getInstance().prettyIndent <= 0) {
        of = OutputFormat.createCompactFormat();
    } else {
        of = OutputFormat.createPrettyPrint();
        of.setIndentSize(ProgramOptions.getInstance().prettyIndent);
    }

    // build data
    DataDstObject data_obj = build_data(compiler);

    // build xml tree
    Document doc = DocumentHelper.createDocument();
    String encoding = SchemeConf.getInstance().getKey().getEncoding();
    if (null != encoding && false == encoding.isEmpty()) {
        doc.setXMLEncoding(encoding);
        of.setEncoding(encoding);
    }

    doc.setRootElement(DocumentHelper.createElement(ProgramOptions.getInstance().xmlRootName));
    doc.getRootElement().addComment("this file is generated by xresloader, please don't edit it.");

    Element header = DocumentHelper.createElement("header");
    Element body = DocumentHelper.createElement("body");
    Element data_message_type = DocumentHelper.createElement("data_message_type");

    writeData(header, data_obj.header, header.getName());

    // body
    for (Map.Entry<String, List<Object>> item : data_obj.body.entrySet()) {
        for (Object obj : item.getValue()) {
            Element xml_item = DocumentHelper.createElement(item.getKey());

            writeData(xml_item, obj, item.getKey());

            body.add(xml_item);
        }
    }

    writeData(body, data_obj.body, body.getName());

    writeData(data_message_type, data_obj.data_message_type, data_message_type.getName());

    doc.getRootElement().add(header);
    doc.getRootElement().add(body);
    doc.getRootElement().add(data_message_type);

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(bos, of);
        writer.write(doc);

        return bos.toByteArray();
    } catch (Exception e) {
        this.logErrorMessage("write xml failed, %s", e.getMessage());
        return null;
    }
}
 
Example 8
Source File: CommonDao.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 生成XML importFile 导出xml工具类
 */
public HttpServletResponse createXml(ImportFile importFile) {
	HttpServletResponse response = importFile.getResponse();
	HttpServletRequest request = importFile.getRequest();
	try {
		// 创建document对象
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		// 创建根节点
		String rootname = importFile.getEntityName() + "s";
		Element rElement = document.addElement(rootname);
		Class entityClass = importFile.getEntityClass();
		String[] fields = importFile.getField().split(",");
		// 得到导出对象的集合
		List objList = loadAll(entityClass);
		Class classType = entityClass.getClass();
		for (Object t : objList) {
			Element childElement = rElement.addElement(importFile.getEntityName());
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i];
				// 第一为实体的主键
				if (i == 0) {
					childElement.addAttribute(fieldName, String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				} else {
					Element name = childElement.addElement(fieldName);
					name.setText(String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				}
			}

		}
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		File fileWriter = new File(ctxPath + "/" + importFile.getFileName());
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(fileWriter));

		xmlWriter.write(document);
		xmlWriter.close();
		// 下载生成的XML文件
		UploadFile uploadFile = new UploadFile(request, response);
		uploadFile.setRealPath(importFile.getFileName());
		uploadFile.setTitleField(importFile.getFileName());
		uploadFile.setExtend("bak");
		viewOrDownloadFile(uploadFile);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return response;
}