/*
* 新建xml文件
*/
public void createXML() {
File fi=new File(xmlPath);
if(!(fi.exists())){
System.out.println("file is exist");
return ;
}
String textXml = null;
textXml = "
"
"
"
"
"
"
"
"
"
"
Reader in= new StringReader(textXml);
SAXBuilder builder = new SAXBuilder();
document=null;
try {
document = builder.build(in);
Format format = Format.getCompactFormat();
format.setEncoding("UTF-8"); //设置xml文件的字符为UTF-8 or gb2312
format.setIndent(" "); //设置xml文件的缩进为4个空格
XMLOutputter outputter = new XMLOutputter(format);
outputter.output(document,new FileOutputStream("config.xml"));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/*
* 读取xml文件
*/
public boolean getLogin(String user,String pass){
List li=null;
SAXBuilder builder=new SAXBuilder();
try{
document=builder.build(new File(xmlPath));
Element root=document.getRootElement();
li=root.getChildren("ROW");
Iterator ii=li.iterator();
while(ii.hasNext()){ //显示
Element root2=(Element) ii.next();
if(root2.getChildText("name").equals(user) && root2.getChildText("pass").equals(pass) ){
System.out.println("找到 "+user+" 的密码:"+root2.getChildText("pass"));
return changXML(root2);
}
}
}catch (Exception e){e.printStackTrace();return false;}
return true;
}
/*
* 修改节点
*/
private boolean changXML(Element root2){
try{
root2.getChild("pass").setText(MD5.MD(root2.getChildText("pass")));
Date da = new Date();
SimpleDateFormat si=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
XMLOutputter outputter=new XMLOutputter();
root2.getChild("date").setText(si.format(da));
outputter.output(document,new FileOutputStream(xmlPath));
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
写了一天才搞定,真晕!!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/790981/viewspace-981339/ ,如需转载,请注明出处,否则将追究法律责任。