dom4j操作工具类


import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class FlowConfigHandle {

String path = ""; //$NON-NLS-1$

File file;

SAXReader saxReader = new SAXReader();

Document document = null;
org.dom4j.io.OutputFormat format = new org.dom4j.io.OutputFormat()
.createPrettyPrint();

public FlowConfigHandle(Document document) {
this.document = document;
path = document.getPath();
}

public FlowConfigHandle(String path) {
try {
// saxReader.setEncoding("UTF-8");
this.path = path;
file = new File(path);
document = saxReader.read(file);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* @param key
* @param isAttribute
* @return
*/
public String get(String key, Boolean isAttribute) {
try {
List list = document.selectNodes(key);
if (list != null && list.size() > 0) {
if (isAttribute) {
return ((Attribute) list.iterator().next()).getText();
} else {
return ((Element) list.iterator().next()).getText();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ""; //$NON-NLS-1$
}

public List getList(String key, Boolean isAttribute) {
try {
if (!isAttribute) {
List list = document.selectNodes(key);
return list;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* @param key
* @param value
* @throws IOException
*/

public void set(String key, String value, Boolean isAttribute) {
try {
if (isAttribute) {
List list = document.selectNodes(key);
((Attribute) list.iterator().next()).setValue(value);
} else {
List list = document.selectNodes(key);
((Element) list.iterator().next()).setText(value);
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* @param key
* @param value
* @throws IOException
*/
public void delete(String key, String value, Boolean isAttribute) {
try {
List list = document.selectNodes(key);
Element element = (Element) list.iterator().next();
if (isAttribute) {
List attributeList = document.selectNodes(key + "/@" + value); //$NON-NLS-1$
Attribute attribute = (Attribute) attributeList.iterator()
.next();
element.remove(attribute);
} else {
List childList = document.selectNodes(key + "/" + value); //$NON-NLS-1$
Element childElement = (Element) childList.iterator().next();
element.remove(childElement);
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* @param key
* @param stringArray
* @param isAttribute
* @throws IOException
*/

public Element insert(String key, String[] stringArray, Boolean isAttribute) {
Element element = null;
try {
List list = document.selectNodes(key);
element = (Element) list.iterator().next();
if (isAttribute) {
element = element.addAttribute(stringArray[0], stringArray[1]);
} else {
element = element.addElement(stringArray[0]);
element.setText(stringArray[1]);
}
} catch (Exception e) {
e.printStackTrace();
}

return element;
}

/**
*
* @param document
* @throws IOException
*/
public void save(Document document) throws IOException {
try {

format.setEncoding("utf-8"); //$NON-NLS-1$
XMLWriter writer = new XMLWriter(new FileWriter(new File(path)),
format);
writer.write(document);
writer.close();
} catch (Exception e) {
e.getStackTrace();
}
}

// public void doSave() throws IOException{
// try{
// document = saxReader.read(file);
// java.io.Writer wr=new java.io.OutputStreamWriter(new
// java.io.FileOutputStream(file),"UTF-8");
// document.write(wr);
// }catch (Exception e){
// e.getStackTrace();
// }
//
// }
public void doSave(){
writeXML(path, document, "UTF-8"); //$NON-NLS-1$
// try {
// format.setEncoding("utf-8");
// document.setXMLEncoding("UTF-8");
// OutputStreamWriter osw = new OutputStreamWriter(new
// FileOutputStream(file),"UTF-8");
// XMLWriter writer = new XMLWriter(osw, format);
// writer.write(document);
// writer.close();
// } catch (Exception e) {
// e.getStackTrace();
// }
}

/**
* @param document
* @return
*/
public Element getRootElement(Document document) {
return document.getRootElement();
}

public void treeWalk(Element element) {
for (int i = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
if (node instanceof Element) {
treeWalk((Element) node);
} else { // do something....
}
}
}

public String getStringFromDocument() {
String text = document.asXML();
return text;
}

public Document getDocument() {
return document;
}

public void setDocument(Document document) {
this.document = document;
}

public void writeXML(String file, Document document, String encoding) {
try {
document.setXMLEncoding("UTF-8"); //$NON-NLS-1$
OutputStreamWriter outWriter = new OutputStreamWriter(
new FileOutputStream(file), "UTF-8"); //$NON-NLS-1$
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(encoding == null ? format.getEncoding()
: encoding);
XMLWriter writer = new XMLWriter(outWriter, format);
writer.write(document);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

public void setDocument(String xml) {
try {
StringReader in = new StringReader(xml);
document = saxReader.read(in);
// System.out.println(document.asXML());
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



网上一些例子


一.Document对象相关

1.读取XML文件,获得document对象.
SAXReader reader = new SAXReader();
Document document = reader.read(new File("input.xml"));


2.解析XML形式的文本,得到document对象.
String text = "<members></members>";
Document document = DocumentHelper.parseText(text);

3.主动创建document对象.
Document document = DocumentHelper.createDocument();
Element root = document.addElement("members");// 创建根节点

二.节点相关

1.获取文档的根节点.
Element rootElm = document.getRootElement();

2.取得某节点的单个子节点.
Element memberElm=root.element("member");// "member"是节点名

3.取得节点的文字
String text=memberElm.getText();
也可以用:
String text=root.elementText("name");
这个是取得根节点下的name字节点的文字.

4.取得某节点下名为"member"的所有字节点并进行遍历.
List nodes = rootElm.elements("member");

for (Iterator it = nodes.iterator(); it.hasNext();) {
Element elm = (Element) it.next();
// do something
}

5.对某节点下的所有子节点进行遍历.
for(Iterator it=root.elementIterator();it.hasNext();){
Element element = (Element) it.next();
// do something
}

6.在某节点下添加子节点.
Element ageElm = newMemberElm.addElement("age");

7.设置节点文字.
ageElm.setText("29");

8.删除某节点.
parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点

三.属性相关.
1.取得某节点下的某属性
Element root=document.getRootElement();
Attribute attribute=root.attribute("size");// 属性名name

2.取得属性的文字
String text=attribute.getText();
也可以用:
String text2=root.element("name").attributeValue("firstname");
这个是取得根节点下name字节点的属性firstname的值.

3.遍历某节点的所有属性
Element root=document.getRootElement();
for(Iterator it=root.attributeIterator();it.hasNext();){
Attribute attribute = (Attribute) it.next();
String text=attribute.getText();
System.out.println(text);
}

4.设置某节点的属性和文字.
newMemberElm.addAttribute("name", "sitinspring");

5.设置属性的文字
Attribute attribute=root.attribute("name");
attribute.setText("sitinspring");

6.删除某属性
Attribute attribute=root.attribute("size");// 属性名name
root.remove(attribute);

四.将文档写入XML文件.
1.文档中全为英文,不设置编码,直接写入的形式.
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
writer.close();

2.文档中含有中文,设置编码格式写入的形式.
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK"); // 指定XML编码
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);

writer.write(document);
writer.close();

五.字符串与XML的转换
1.将字符串转化为XML
String text = "<members> <member>sitinspring</member> </members>";
Document document = DocumentHelper.parseText(text);

2.将文档或节点的XML转化为字符串.
SAXReader reader = new SAXReader();
Document document = reader.read(new File("input.xml"));
Element root=document.getRootElement();
String docXmlText=document.asXML();
String rootXmlText=root.asXML();
Element memberElm=root.element("member");
String memberXmlText=memberElm.asXML();

六.使用XPath快速找到节点.
读取的XML文档示例
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>MemberManagement</name>
<comment></comment>
<projects>
<project>PRJ1</project>
<project>PRJ2</project>
<project>PRJ3</project>
<project>PRJ4</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

使用XPath快速找到节点project.
public static void main(String[] args){
SAXReader reader = new SAXReader();

try{
Document doc = reader.read(new File("sample.xml"));

List projects=doc.selectNodes("/projectDescription/projects/project");

Iterator it=projects.iterator();

while(it.hasNext()){
Element elm=(Element)it.next();
System.out.println(elm.getText());
}

}
catch(Exception ex){
ex.printStackTrace();
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值