使用dom4j处理xml文件
1.项目中加入dom4j的jar
2.基本的读取xml文件为Document对象;将Document对象写入到指定文件中
package com.ricoh.rapp.deploymenttool.util; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; import com.ricoh.rapp.deploymenttool.util.Consts; public class XmlParser { private final static Log logger = LogFactory.getLog(XmlParser.class);
/**
* Read from xml file.
* @param file
* @return
*/
public static Document readXML(File file) {
Document document = null;
SAXReader saxReader = new SAXReader();
saxReader.setEncoding(Consts.UTF8_ENCODING);
if (!file.exists()) {
String logInfo = "No device/Cloud Connector registered. File " + file.getName() + " not exists.";
logger.debug(logInfo);
return null;
}
try {
document = saxReader.read(file);
} catch (DocumentException e) {
String logInfo = "No device/Cloud Connector registered. File " + file.getName() + " is wrong. ";
if (e != null) {
logInfo = logInfo + e.toString();
}
logger.error(logInfo);
return null;
}
return document;
} public static boolean writeXML(Document document, File file) {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(Consts.UTF8_ENCODING);
XMLWriter writer = null;
try {
writer = new XMLWriter(new FileOutputStream(file), format);
writer.write(document);
return true;
} catch (IOException e) {
String logInfo = "Write xml file " + file.getName() + " failed!";
logger.error(logInfo);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
logger.debug("Close file " + file.getName() + " fialed. " + e.toString());
}
}
}
return false;
}
}
3.解析xml文件、修改文件、创建xml文件。
package com.ricoh.rapp.deploymenttool.util; import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element; import com.ricoh.rapp.deploymenttool.ui.RSICloudModel;
import com.ricoh.rapp.deploymenttool.ui.RSICloudModel.FunctionKey;
import com.ricoh.rapp.deploymenttool.ui.RSICloudModel.FunctionKeyOptions;
import com.ricoh.rapp.deploymenttool.util.Consts;
import com.ricoh.rapp.deploymenttool.util.XmlParser; public class RSICloudXmlParser extends XmlParser{ private static final Log logger = LogFactory.getLog(RSICloudXmlParser.class); private static final File file = new File(Consts.RSICLOUD_FILE_PATH);
private static final File initialFile = new File(Consts.RSICLOUD_INITIAL_FILE_PATH); public static final String initialUrl = "https://www.na.smart-integration.ricoh.com/si-apps/pub/index.html"; private static final String ELEMENT_ROOT = "root";
private static final String ELEMENT_FUNCTIONKEY_SETTINGS = "FunctionKeySettings";
private static final String ELEMENT_FUNCASSIGN = "FuncAssign";
private static final String ELEMENT_DISPLAY = "Display";
private static final String ELEMENT_FUNCKEYS = "FuncKeys";
private static final String ELEMENT_FUNC = "Func";
private static final String ELEMENT_WEBBROWSER_NXSETTINGS = "WebBrowserNXSettings";
private static final String ELEMENT_HOMEPAGE = "HomePage";
private static final String ATTR_ENABLED = "enabled";
private static final String ATTR_ID = "id";
private static final String ATTR_SELECTED = "selected";
private static final String ATTR_VALUE_TRUE = "true";
private static final String ATTR_VALUE_FALSE = "false"; public static RSICloudModel parseRSICloudXML(){
logger.info("parseRSICloudXML file: " + initialFile.getName());
logger.info("parseRSICloudXML file: " + file.getName());
Document document = null;
if(file.exists()) {
document = readXML(file);
}else {
document = readXML(initialFile);
} return xmlFileToBean(document);
} public static RSICloudModel resetParseRSICloudXML(){
logger.info("parseRSICloudXML file: " + initialFile.getName());
Document document = readXML(initialFile);
return xmlFileToBean(document);
} private static RSICloudModel xmlFileToBean(Document document) {
RSICloudModel rsiCloud = new RSICloudModel();
if(document == null) {
return rsiCloud;
}
Element root = document.getRootElement();
if(root == null) {
return rsiCloud;
}
Element fkSettingsEle = root.element(ELEMENT_FUNCTIONKEY_SETTINGS);
Element wbSettingsEle = root.element(ELEMENT_WEBBROWSER_NXSETTINGS);
if (fkSettingsEle == null && wbSettingsEle == null) {
return rsiCloud;
} String fkEnabled = fkSettingsEle.attributeValue(ATTR_ENABLED);
rsiCloud.setFunctionKeySettings(stringToBln(fkEnabled));
List<FunctionKey> functionKeys = new ArrayList<>();
for(Iterator rsiCloudsIterator = fkSettingsEle.elementIterator(ELEMENT_FUNCASSIGN); rsiCloudsIterator.hasNext();) {
Element funcAssignEle = (Element) rsiCloudsIterator.next();
FunctionKey FunctionKey = rsiCloud.new FunctionKey();
String id = funcAssignEle.attributeValue(ATTR_ID);
String isSelected = funcAssignEle.attributeValue(ATTR_SELECTED);
String dispalyName = funcAssignEle.element(ELEMENT_DISPLAY).getText(); FunctionKey.setId(Integer.parseInt(id));
FunctionKey.setFuncAssign(stringToBln(isSelected));
FunctionKey.setDispalyName(dispalyName);
List<FunctionKeyOptions> functionKeyOptions = new LinkedList<>();
for(Iterator funcIterator = funcAssignEle.element(ELEMENT_FUNCKEYS).elementIterator(ELEMENT_FUNC); funcIterator.hasNext();) {
Element funcEle = (Element) funcIterator.next();
FunctionKeyOptions functionKeyOption = rsiCloud.new FunctionKeyOptions();
String selectedOpt = funcEle.attributeValue(ATTR_SELECTED);
String optValue = funcEle.getText();
functionKeyOption.setSelected(stringToBln(selectedOpt));
functionKeyOption.setChoiceValues(optValue);
functionKeyOptions.add(functionKeyOption);
}
FunctionKey.setFunctionKeyOptions(functionKeyOptions); functionKeys.add(FunctionKey);
} rsiCloud.setFunctionKeys(functionKeys);
String wbEnabled = wbSettingsEle.attributeValue(ATTR_ENABLED);
rsiCloud.setWebBrowserNXSettings(stringToBln(wbEnabled));
String homePageUrl = wbSettingsEle.element(ELEMENT_HOMEPAGE).getText();
rsiCloud.setHomePageUrl(homePageUrl);
return rsiCloud;
} public static boolean saveCustomSettings(RSICloudModel rsiCloud) {
if(file.exists()) {
return updateRSICloudXML(rsiCloud);
}else {
return createRSICloudXml(rsiCloud);
}
} public static boolean updateRSICloudXML(RSICloudModel rsiCloud) {
Document document = readXML(file);
if(document == null || rsiCloud == null) {
return false;
}
Element root = document.getRootElement(); Element fkSettingsEle = root.element(ELEMENT_FUNCTIONKEY_SETTINGS); boolean functionKeySettings = rsiCloud.isFunctionKeySettings();
fkSettingsEle.addAttribute(ATTR_ENABLED, booleanToStr(functionKeySettings)); List<FunctionKey> functionKeys = rsiCloud.getFunctionKeys(); for(Iterator rsiCloudsIterator = fkSettingsEle.elementIterator(ELEMENT_FUNCASSIGN); rsiCloudsIterator.hasNext();) {
Element funcAssignEle = (Element) rsiCloudsIterator.next(); int id = Integer.parseInt(funcAssignEle.attributeValue(ATTR_ID)); for(FunctionKey functionKey : functionKeys) {
if(functionKey.getId() == id) {
boolean isSelected = functionKey.isFuncAssign();
funcAssignEle.addAttribute(ATTR_SELECTED, booleanToStr(isSelected));
String displayName = functionKey.getDispalyName().trim();
funcAssignEle.element(ELEMENT_DISPLAY).setText(displayName); for(Iterator funcIterator = funcAssignEle.element(ELEMENT_FUNCKEYS).elementIterator(ELEMENT_FUNC); funcIterator.hasNext();) {
Element funcEle = (Element) funcIterator.next();
String funcValue = funcEle.getText();
List<FunctionKeyOptions> functionKeyOptions = functionKey.getFunctionKeyOptions();
for(FunctionKeyOptions functionKeyOption : functionKeyOptions) {
if(functionKeyOption.isSelected() && funcValue.trim().equals(functionKeyOption.getChoiceValues().trim())) {
funcEle.addAttribute(ATTR_SELECTED, booleanToStr(true));
} if(!functionKeyOption.isSelected() && funcValue.trim().equals(functionKeyOption.getChoiceValues().trim())) {
funcEle.remove(funcEle.attribute(ATTR_SELECTED));
}
}
}
}
}
} Element wbSettingsEle = root.element(ELEMENT_WEBBROWSER_NXSETTINGS);
boolean webBrowserSetting = rsiCloud.isWebBrowserNXSettings();
wbSettingsEle.addAttribute(ATTR_ENABLED, booleanToStr(webBrowserSetting));
String homePageUrl = rsiCloud.getHomePageUrl();
wbSettingsEle.element(ELEMENT_HOMEPAGE).setText(homePageUrl); writeXML(document, file); return true;
} private static boolean createRSICloudXml(RSICloudModel rsiCloud) {
if(file.isFile() && file.exists()) {
return true;
}else {
try {
file.createNewFile();
} catch (IOException e) {
logger.error("createRSICloudXml failed:File name: " + file.getName() + ", File path:" + file.getAbsolutePath()
+ ", IOException:" + e.getMessage());
}
}
if(rsiCloud == null) return false; Document document = DocumentHelper.createDocument(); Element root = document.addElement(ELEMENT_ROOT);
Element fkSettingsEle = root.addElement(ELEMENT_FUNCTIONKEY_SETTINGS);
if(rsiCloud.isFunctionKeySettings()) {
fkSettingsEle.addAttribute(ATTR_ENABLED, ATTR_VALUE_TRUE);
}else {
fkSettingsEle.addAttribute(ATTR_ENABLED, ATTR_VALUE_FALSE);
} for(FunctionKey functionKey : rsiCloud.getFunctionKeys()) {
Element funcAssignEle = fkSettingsEle.addElement(ELEMENT_FUNCASSIGN);
funcAssignEle.addAttribute(ATTR_ID, String.valueOf(functionKey.getId()));
funcAssignEle.addAttribute(ATTR_SELECTED, ATTR_VALUE_TRUE);
if(functionKey.isFuncAssign()) {
funcAssignEle.addAttribute(ATTR_SELECTED, ATTR_VALUE_TRUE);
}else {
funcAssignEle.addAttribute(ATTR_SELECTED, ATTR_VALUE_FALSE);
} Element displayEle = funcAssignEle.addElement(ELEMENT_DISPLAY);
displayEle.setText(functionKey.getDispalyName()); Element funcKeysEle = funcAssignEle.addElement(ELEMENT_FUNCKEYS);
for(FunctionKeyOptions functionKeyOption :functionKey.getFunctionKeyOptions()) {
Element funcEle = funcKeysEle.addElement(ELEMENT_FUNC);
funcEle.setText(functionKeyOption.getChoiceValues());
if(functionKeyOption.isSelected()) funcEle.addAttribute(ATTR_SELECTED, ATTR_VALUE_TRUE);
} } Element webBrowSettingsEle = root.addElement(ELEMENT_WEBBROWSER_NXSETTINGS);
if(rsiCloud.isWebBrowserNXSettings()) {
webBrowSettingsEle.addAttribute(ATTR_ENABLED, ATTR_VALUE_TRUE);
}else {
webBrowSettingsEle.addAttribute(ATTR_ENABLED, ATTR_VALUE_FALSE);
}
Element homePageEle = webBrowSettingsEle.addElement(ELEMENT_HOMEPAGE);
homePageEle.setText(rsiCloud.getHomePageUrl()); return writeXML(document, file);
} public static boolean stringToBln(String str) {
if(str != null && ATTR_VALUE_TRUE.equals(str.trim())) {
return true;
}
return false;
} public static String booleanToStr(boolean bln) {
if(bln) {
return ATTR_VALUE_TRUE;
}else {
return ATTR_VALUE_FALSE;
}
} public static void main(String[] args) throws IOException {
/*RSICloudModel rsiCloud = RSICloudXmlParser.parseRSICloudXML();
for(FunctionKey functionKey: rsiCloud.getFunctionKeys()) {
if(functionKey.getId() == 0) {
functionKey.getFunctionKeyOptions().toArray();
}
}*/ // createRSICloudXml(null);
System.out.println(initialUrl);
} }
3.自定义xml文件实例
<?xml version="1.0" encoding="UTF-8"?> <root>
<FunctionKeySettings enabled="false">
<FuncAssign id="0" selected="true">
<Display>Display node value</Display>
<FuncKeys>
<Func/>
<Func>func node value1</Func>
<Func>func node value2</Func>
<Func selected="true">func node value3</Func>
<Func>func node value4</Func>
</FuncKeys>
</FuncAssign>
<FuncAssign id="1" selected="true">
<Display>Display node value3</Display>
<FuncKeys>
<Func/>
<Func>func node value1</Func>
<Func>func node value2</Func>
<Func>func node value3</Func>
<Func>func node value4</Func>
<Func selected="true">func node value5</Func>
</FuncKeys>
</FuncAssign>
<FuncAssign id="2" selected="false">
<Display></Display>
<FuncKeys>
<Func selected="true"/>
<Func>func node value1</Func>
<Func>func node value2</Func>
<Func>func node value3</Func>
<Func>func node value4</Func>
<Func>func node value5</Func>
<Func>func node value6</Func>
</FuncKeys>
</FuncAssign>
</FunctionKeySettings>
<WebBrowserNXSettings enabled="true">
<HomePage>https://www.baidu.com</HomePage>
</WebBrowserNXSettings>
</root>
使用dom4j处理xml文件的更多相关文章
- 【dom4j xml】使用dom4j处理XML文件--测试过程遇到的问题
首先 关于dom4j的API,有如下: 当然 其中的实体引用有以下: 测试使用环境: 使用Maven搭建web环境,pom.xml文件配置如下: <project xmlns="ht ...
- 【JAVA使用XPath、DOM4J解析XML文件,实现对XML文件的CRUD操作】
一.简介 1.使用XPath可以快速精确定位指定的节点,以实现对XML文件的CRUD操作. 2.去网上下载一个“XPath帮助文档”,以便于查看语法等详细信息,最好是那种有很多实例的那种. 3.学习X ...
- 用DOM4J解析XML文件案例
用DOM4J解析XML文件案例,由于DOM4J不像JAXP属于JAVASE里,所以如果要使用DOM4J,则必须额外引入jar包,如图:
- 使用DOM4J解析XMl文件与读取XML文件
XML文件 <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book id ...
- 使用dom4j对xml文件进行增删改查
1.使用dom4j技术对dom_demo.xml进行增删改查 首选要下载dom4j的jar包 在官网上找不到,网上搜索了一下在这个链接:http://sourceforge.net/projects/ ...
- Dom4j解析Xml文件,Dom4j创建Xml文件
Dom4j解析Xml文件,Dom4j创建Xml文件 >>>>>>>>>>>>>>>>>>&g ...
- 使用dom4j解析xml文件,并封装为javabean对象
dom4j是一个java的XML api,性能优异.功能强大.易于使用.这里使用dom4j对xml文件进行解析,并完成对文件的封装. 实现对xml文件的解析,主要使用到的是dom4j中的SAXRead ...
- 使用dom4j 读取XML文件
第一次接触dom4j的时候,感觉这个东西很神秘,因为之前虽然知道XML文件吧,但从来没有用过,一直感觉XML肯定不好操作.当得知,dom4j可以很容易的操作读取XML文件时,不免有些好奇,那么,用do ...
- DOM4J读取XML文件
最近在做DRP的项目,其中涉及到了读取配置文件,用到了DOM4J,由于是刚开始接触这种读取xml文件的技术,好奇心是难免的,于是在网上又找了一些资料,这里就结合找到的资料来谈一下读取xml文件的4中方 ...
- Java进阶(二十七)使用Dom4j解析XML文件
使用Dom4j解析XML文件 写在前面的话 由于论文实验要求,需要实现操作XML文档,为此想到了dom4j这个工具,使用之后深感受益.在此分享给大家,以此共勉. 注:本文转载自http://blog. ...
随机推荐
- windows内核基础与异常处理
前两日碰到了用异常处理来做加密的re题目 所以系统学习一下windows内核相关 windows内核基础 权限级别 内核层:R0 零环 核心态工作区域 大多数驱动程序 应用层:R3 用户态工作区域 只 ...
- 36、python并发编程之多线程(操作篇)
目录: 一 threading模块介绍 二 开启线程的两种方式 三 在一个进程下开启多个线程与在一个进程下开启多个子进程的区别 四 练习 五 线程相关的其他方法 六 守护线程 七 Python GIL ...
- KC705E增强版基于FMC接口的 Kintex-7 XC7K325T PCIeX8 接口卡
一.板卡概述 本板卡基于Xilinx公司的FPGAXC7K325T-2FFG900 芯片,pin_to_pin兼容FPGAXC7K410T-2FFG900 ,支持PCIeX8.64bit DDR3容量 ...
- C++奇异递归模板模式
虚函数的问题 虚函数的主要问题是性能开销比较大,一个虚函数调用可能需要花费数倍于非虚函数调用的时间,尤其是当非虚函数被声明为inline时(注意,虚函数不能被内联). CRTP介绍 CRTP的全称是C ...
- Visual Studio Code 配置C、C++ 文件debug调试环境
目录 vscode C/C++ Extension Pack 插件安装 vscode windows 端 debug 配置 window MinGW 环境安装 windows 端 C.CPP 单文件 ...
- 乘风破浪,遇见未来元宇宙(Metaverse)之进入元宇宙世界,虚拟数字人行业洞察报告
正值元宇宙热潮,虚拟数字人兴起 作为⼀个新兴领域,虚拟数字⼈已经引起市场和资本的⾼度关注,截⾄目前据不完全统计,全球范围已有500+虚拟数字人相关项目获得融资,融资总额超10亿美元,并且融资项目和总额 ...
- Python中编码encode()与解码decode()
1 print('这是编码'.encode('utf-8')) # 结果 b'\xe8\xbf\x99\xe6\x98\xaf\xe7\xbc\x96\xe7\xa0\x81' 2 print('这是 ...
- volatile关键字的相关学习记录
1:volatile是什么? Volatile是java虚拟机提供的一种轻量级的同步机制,具有 三大特性,分别是:保证可见性.不保证原子性.禁止指令重排 可见性: 概念:每一个线程都有自己的工作内存, ...
- Selenium自动化测试面试题合集
1.什么是自动化测试.自动化测试的优势是什么? 通过工具或脚本代替手工测试执行过程的测试都叫自动化测试. 自动化测试的优势: 1.减少回归测试成本 2.减少兼容性测试成本 3.提高测试反馈速度 4.提 ...
- k8s搭建监控:安装metrics server和dashboard
安装metrics server 参考:https://github.com/kubernetes-sigs/metrics-server kubectl create -f component ...