首页 > 代码库 > 用java新建xml文件和读取
用java新建xml文件和读取
//新建一个xml文档
private static void createXml(String path) throws UnsupportedEncodingException, FileNotFoundException, IOException {
//创建根节点
Element rootElement = DocumentHelper.createElement("student");
rootElement.addAttribute("sno", "20160810001");
//创建子节点
Element unameElement = DocumentHelper.createElement("uname");
unameElement.setText("张三");
Element pwdElement = DocumentHelper.createElement("pwd");
pwdElement.setText("123456");
rootElement.add(unameElement);
rootElement.add(pwdElement);
//创建一个文档
Document document = DocumentHelper.createDocument(rootElement);
//写出到硬盘
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter writer = new XMLWriter(new FileOutputStream(path), format);
writer.write(document);
}
用java新建xml文件和读取