import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.List;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.dom4j.Attribute;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.dom4j.io.DocumentResult;

import org.dom4j.io.DocumentSource;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;

/**

* XML读写工具

* @author csx

*

*/

public class XmlUtil {

private static final Log logger=LogFactory.getLog(XmlUtil.class);

public static final String CONFIG_FILE_NAME = "hurong.xml";// 系统配置文件名称

public static Document getSystemConfigXML(){

try{

Document document = null;

File configFile = null;

String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()+"hurong.xml";

configFile = new File(configFilePath);

SAXReader saxReader = new SAXReader();

document = saxReader.read(configFile);

return document;}

catch (Exception e) {

e.printStackTrace();

return null;

}

}

/**

*

* 获取第三方短信、身份证验证接口

*

*

* **/

public  static Document getThridInterface(){

try{

Document document = null;

File configFile = null;

String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()+"thridInterface.xml";

configFile = new File(configFilePath);

SAXReader saxReader = new SAXReader();

document = saxReader.read(configFile);

return document;}

catch (Exception e) {

e.printStackTrace();

return null;

}

}

/**

* 把Document对象转成XML String

* @param document

* @return

*/

public static String docToString(Document document) {

String s = "";

try {

ByteArrayOutputStream out = new ByteArrayOutputStream();

OutputFormat format = new OutputFormat("  ", true, "UTF-8");

XMLWriter writer = new XMLWriter(out, format);

writer.write(document);

s = out.toString("UTF-8");

} catch (Exception ex) {

logger.error("docToString error:"+ex.getMessage());

}

return s;

}

/**

* 把XML String转成Document对象

* @param s

* @return

*/

public static Document stringToDocument(String s) {

Document doc = null;

try {

doc = DocumentHelper.parseText(s);

} catch (Exception ex) {

logger.error("stringToDocument error:"+ex.getMessage());

}

return doc;

}

/**

* 把Document对象转成XML对象

* @param document

* @param filename

* @return

*/

public static boolean docToXmlFile(Document document, String filename) {

boolean flag = true;

try {

OutputFormat format = OutputFormat.createPrettyPrint();

format.setEncoding("UTF-8");

XMLWriter writer = new XMLWriter(

new FileOutputStream(new File(filename)), format);

writer.write(document);

writer.close();

} catch (Exception ex) {

flag = false;

logger.error("docToXmlFile error:"+ex.getMessage());

}

return flag;

}

/**

* 把String XML转成XML文件

* @param str

* @param filename

* @return

*/

public static boolean stringToXmlFile(String str, String filename) {

boolean flag = true;

try {

Document doc = DocumentHelper.parseText(str);

flag = docToXmlFile(doc, filename);

} catch (Exception ex) {

flag = false;

logger.error("stringToXmlFile error:"+ex.getMessage());

}

return flag;

}

/**

* 加载一个XML文件转成Document对象

* @param filename

* @return

*/

public static Document load(String filename) {

return load(new File(filename));

}

public static Document load(File file){

Document document = null;

try {

SAXReader saxReader = new SAXReader();

saxReader.setEncoding("UTF-8");

document = saxReader.read(file);

} catch (Exception ex) {

logger.error("load XML File error:"+ex.getMessage());

}

return document;

}

/**

* 加载一个XML文件转成Document对象

* @param filename

* @return

*/

public static Document load(String filename,String encode) {

Document document = null;

try {

SAXReader saxReader = new SAXReader();

saxReader.setEncoding("encode");

document = saxReader.read(new File(filename));

} catch (Exception ex) {

logger.error("load XML File error:"+ex.getMessage());

}

return document;

}

/**

* 通过流加载一个XML文档对象

* @param is

* @return

*/

public static Document load(InputStream is){

Document document = null;

try {

SAXReader saxReader = new SAXReader();

//System.out.println("code:" + System.getProperty("file.encoding"));

saxReader.setEncoding("UTF-8");

document = saxReader.read(is);

} catch (Exception ex) {

logger.error("load XML File error:"+ex.getMessage());

}

return document;

}

/**

* 通过流加载一个XML文档对象

* @param is

* @return

*/

public static Document load(InputStream is,String encode){

Document document = null;

try {

SAXReader saxReader = new SAXReader();

saxReader.setEncoding(encode);

document = saxReader.read(is);

} catch (Exception ex) {

logger.error("load XML File error:"+ex.getMessage());

}

return document;

}

public static Document styleDocument(

Document document,

String stylesheet

) throws Exception {

// load the transformer using JAXP

TransformerFactory factory = TransformerFactory.newInstance();

Transformer transformer = factory.newTransformer(

new StreamSource( stylesheet )

);

// now lets style the given document

DocumentSource source = new DocumentSource( document );

DocumentResult result = new DocumentResult();

transformer.transform( source, result );

// return the transformed document

Document transformedDoc = result.getDocument();

return transformedDoc;

}

public static void main(String[]args){

String filePath="L:/devtools/workspace/eoffice/web/js/menu.xml";

String style="L:/devtools/workspace/eoffice/web/js/menu-public.xsl";

Document doc=XmlUtil.load(filePath);

try{

Document another=styleDocument(doc,style);

System.out.println("xml:" + another.asXML());

//Set idSet=new HashSet();

Document publicDoc=another;

Element rootEl=publicDoc.getRootElement();

List idNodes=rootEl.selectNodes("/Menus//*");

System.out.println("size:" + idNodes.size());

for(int i=0;i<idNodes.size();i++){

Element el=(Element)idNodes.get(i);

Attribute attr= el.attribute("id");

if(attr!=null){

System.out.println("attr:" + attr.getValue());

//idSet.add(attr.getValue());

}

}

}catch(Exception ex){

ex.printStackTrace();

}

}

}

XML读写工具的更多相关文章

  1. XML读写工具类

    摘要:①读取XML文件,生成pojo对象:②将对象信息保存到xml中. 步骤: ①新建一个普通的java类BasePage: package com.test.selenium.pages; impo ...

  2. 【Python】Python XML 读写

    class ACTIVE_FILE_PROTECT_RULE_VIEW(APIView): renderer_classes = (JSONRenderer, BrowsableAPIRenderer ...

  3. Java XML解析工具 dom4j介绍及使用实例

    Java XML解析工具 dom4j介绍及使用实例 dom4j介绍 dom4j的项目地址:http://sourceforge.net/projects/dom4j/?source=directory ...

  4. XML编辑工具

    [标题]XML编辑工具 [开发环境]Qt 5.2.0 [概要设计]使用QT的视图/模型结构.treeview控件以树形结构显示所要操作的XML文件,并实现xml的相关操作 [详细设计] 主要包含 no ...

  5. ntfs读写工具Paragon NTFS 15无限使用教程

    Paragon NTFS mac版是Mac OS平台上最受欢迎的ntfs读写工具,专门开发用来弥补Windows和Mac OS X之间的不兼容性,通过在Mac OS X系统下提供对任何版本的NTFS文 ...

  6. properties文件读写工具类

    java代码: import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; ...

  7. 在Android源码树中添加userspace I2C读写工具(i2c-util)

    在Android源码树中添加userspace I2C读写工具(i2c-util) http://blog.csdn.net/21cnbao/article/details/7919055 分类: A ...

  8. jsonUtils&&Json、Xml转换工具Jackson使用

    1.jsonUtils package com.icil.utils; import java.util.List; import com.fasterxml.jackson.core.JsonPro ...

  9. Spring-Boot ☞ ShapeFile文件读写工具类+接口调用

    一.项目目录结构树 二.项目启动 三.往指定的shp文件里写内容 (1) json数据[Post] { "name":"test", "path&qu ...

随机推荐

  1. elasticsearch使用ansj分词器

    目前elasticsearch的版本已经更新到7.0以上了,不过由于客户需要5.2.2版本的elasticsearch,所以还是需要安装的,并且安装上ansj分词器.在部署ES的时候,采用容器的方式进 ...

  2. git 学习笔记 —— 保留/丢弃当前分支修改并切换至其他分支

    笔者在本地终端进行 git 工作目录的相关处理时,遇到由于某种情况需要使用 git checkout 命令切换到其他分支的情景.此时,若已经对当前分支做了一定的修改,则直接切换分支时 git 会提示错 ...

  3. cmds在线重定义增加列

    --输出信息采用缩排或换行格式化 EXEC DBMS_METADATA.set_transform_param(DBMS_METADATA.session_transform, 'PRETTY', T ...

  4. MANIFEST.MF文件对Import-Package/Export-Package重排列

    众所周知,MANIFEST.MF文件中的空格开头的行是相当于拼接在上一行末尾的.很多又长又乱的Import-Package或者Export-Package,有时候想要搜索某个package却可能被换行 ...

  5. Gamification vs. Game-Based Learning

    http://www.immersedgames.com/gamification-vs-game-based-learning/ With the growth in popularity of v ...

  6. HTTP权威指南 目录

    diyi部分 HTTP:Web的基础 第1章 HTTP概述 31.1 HTTP——因特网的多媒体信使 41.2 Web客户端和服务器 41.3 资源 51.3.1 媒体类型 61.3.2 URI 71 ...

  7. flutter中的异步机制Future

    饿补一下Flutter中Http请求的异步操作. Dart是一个单线程语言,可以理解成物理线路中的串联,当其遇到有延迟的运算(比如IO操作.延时执行)时,线程中按顺序执行的运算就会阻塞,用户就会感觉到 ...

  8. Xml与Map之间的相互转换

    一.(单层)xml转换为map /** * XML格式字符串转换为Map * * @param xml XML字符串 * @return XML数据转换后的Map * @throws Exceptio ...

  9. vue使用插件的流程

    1.引入vue 2.引入插件 3.通过vue.use()调用 例子:使用router插件 import Vue from "vue"; import VueRouter from ...

  10. connect via ssh to virtualbox guest vm without knowing ip address

    cat ssh-vm HOSTIP=`ip route get 1 | awk '{match($0, /.+src\s([.0-9]+)/, a);print a[1];exit}'` HOST_N ...