1.首先要加入dom4j-1.6.1.jar和jaxen-1.1-beta-7.jar,否则会出现异常
2.java代码部分:
public class FileXML {
static final String PATH = "F:/work/temp/test01/WEB-INF/file/";
File file;
Document doc;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
FileXML fxml = new FileXML();
fxml.file = new File(PATH+"text"+".xml");
// fxml.createFile();
fxml.writerFile("a","id",1);
// fxml.writerFile("b","id",2);
// fxml.writerFile("c","id",3);
// fxml.updateAttributeValue("b","id",8);
}
//创建.xml文件
public void createFile() {
try{
doc = DocumentHelper.createDocument();
Element root = doc.addElement("elments");
this.toXML();
}catch(Exception e){
System.out.print("文件创建失败!");
e.printStackTrace();
}
System.out.print("文件已创建!");
}
/**
* 添加.xml文件内容
* @param nodeName 节点名称
* @param attributeName 属性名称
* @param attrValue 属性值
* @throws IOException
*/
public void writerFile(String nodeName,String attributeName,int attValue){
//构造SAX解析器
SAXReader sr = new SAXReader();
try {
//获取要处理的文本对象doc
doc = sr.read(file);
//获取根节点
Element root=doc.getRootElement();
//判断要创建的节点是否存在。不存在则创建
if(root.element(nodeName)==null){
Element elements = root.addElement(nodeName);
elements.addAttribute(attributeName, ""+attValue);
}
this.toXML();
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* 修改节点的属性值
* @param nodeName 节点名称
* @param attributeName 属性名称
* @param attValue 属性值
*/
public void updateAttributeValue(String nodeName,String attributeName,int attValue){
//构造SAX解析器
SAXReader sr = new SAXReader();
try {
//获取要处理的文本对象doc
doc = sr.read(file);
//获取根节点
Element root=doc.getRootElement();
//获取节点的属性
Attribute att=root.element(nodeName).attribute(attributeName);
att.setValue(""+attValue);
this.toXML();
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* 加载到.xml文件中
*/
public void toXML(){
OutputStream out;
XMLWriter writer = new XMLWriter();
try {
out = new FileOutputStream(file);
writer.setOutputStream(out);
writer.write(doc);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}