/**
* 获取Document对象
* @param fileName xml位置
* @return String 值
* @throws Exception
*/
public Document getXMLDocument(String fileName){
fileName = Constants.CONF_PATH+fileName;
File file = new File(fileName);
SAXReader reader = new SAXReader();
reader.setEncoding("UTF-8");
Document document = null;
try {
document = reader.read(file);
} catch (DocumentException e) {
logger.info("解析文件出错!");
}
return document;
}
遍历所有节点
//遍历当前节点下的所有节点
public void listNodes(Element node){
System.out.println("当前节点的名称:" + node.getName());
//首先获取当前节点的所有属性节点
List<Attribute> list = node.attributes();
//遍历属性节点
for(Attribute attribute : list){
System.out.println("属性"+attribute.getName() +":" + attribute.getValue());
}
//如果当前节点内容不为空,则输出
if(!(node.getTextTrim().equals(""))){
System.out.println( node.getName() + ":" + node.getText());
}
//同时迭代当前节点下面的所有子节点
//使用递归
Iterator<Element> iterator = node.elementIterator();
while(iterator.hasNext()){
Element e = iterator.next();
listNodes(e);
}
}
获取节点属性值
/**
* 根据节点名称获取值
* @param fileName 文件名称
* @param nodeName1 节点1
* @param nodeName2 节点2(可为空)
* @return
* @throws DocumentException
*/
public String getNodeValue(String fileName,String nodeName1,String nodeName2) throws DocumentException {
Document document = getXMLDocument(fileName);
Element root = document.getRootElement();
Element node1 = root.element(nodeName1);
System.out.println(node1.getName()+":"+node1.getText());
if(StringUtils.isEmptyOrNull(nodeName2)){
return node1.getText();
}
Element node2 = node1.element(nodeName2);
System.out.println(node2.getName()+":"+node2.getText());
return node2.getText();
}
/**
* 设置节点属性值
* @param fileName 文件名
* @param value 设置的值
* @param nodeName1 节点名
* @param nodeName2 节点名(如没有可赋空)
* @throws DocumentException
* @throws IOException
*/
public void setXmlValue(String fileName,String value,String nodeName1,String nodeName2) throws DocumentException, IOException {
Document document = getXMLDocument(fileName);
Element root = document.getRootElement();
Element node1 = root.element(nodeName1);
System.out.println(node1.getName()+":"+node1.getText());
if(StringUtils.isEmptyOrNull(nodeName2)){
node1.setText(value);
System.out.println("改变后的值为:"+node1.getText());
}else{
Element node2 = node1.element(nodeName2);
node2.setText(value);
System.out.println(node2.getName()+"改变后的值为:"+node2.getText());
}
writeXml(document,fileName);
}
/**
* 输出xml文件
*
* @param document
* @param filePath
* @throws IOException
*/
public static void writeXml(Document document, String filePath) throws IOException {
File xmlFile = new File(filePath);
XMLWriter writer = null;
try {
if (xmlFile.exists())
xmlFile.delete();
writer = new XMLWriter(new FileOutputStream(xmlFile), OutputFormat.createPrettyPrint());
writer.write(document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
writer.close();
}
}
测试main函数
public static void main(String[] args) throws Exception {
XmlTools tool = new XmlTools();
tool.setXmlValue("settings.xml","3","interval","");
}