<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/css" href=""?>
<!--
version:xml版本
encoding:xml编码
standalong:是否需要依赖其他文件
-->
<user>
<info>
<username>rabbit</username>
<password>fat</password>
</info>
</user>
/**
* 获取document对象
*
* @param path xml路径
* @return
* @throws DocumentException
*/
private Document getDocumentObject(String path) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(path);
return document;
}
/**
* 解析xml
* @throws DocumentException
*/
private void paramXML() throws DocumentException {
Document document = getDocumentObject(this.getClass().getResource("/").getPath() + "../../xml/test.xml");
Element e = document.getRootElement();
Iterator iterator = e.elementIterator();
while (iterator.hasNext()) {
Element next = (Element) iterator.next();
String username = next.elementTextTrim("username");
String password = next.elementTextTrim("password");
System.out.println("username=" + username + ",password=" + password);
}
}
/**
* 添加节点
* @param ub
* @throws DocumentException
*/
public void writeXML(UserBean ub) throws DocumentException {
SAXReader reader = new SAXReader();
String path = this.getClass().getResource("/").getPath() + "../../xml/test.xml";
Document document = reader.read(path);
Element rootElement = document.getRootElement();
Element element = rootElement.addElement("info");
//添加子节点
Element username = element.addElement("username");
//设置节点文字
username.setText(ub.getUsername());
Element password = element.addElement("password");
password.setText(ub.getPassword());
Element phone = element.addElement("phone");
phone.setText(ub.getPhone());
Element email = element.addElement("email");
email.setText(ub.getEmail());
try {
//写入到文件
OutputFormat of = OutputFormat.createPrettyPrint();
of.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileWriter(path), of);
writer.write(document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}