Java dom4j生成XML文件的方法分享
下文讲述使用dom4j生成XML文件的方法分享,如下所示:
dom4j创建xml的方法分享
1.创建一个文档模型
Document document = DocumentHelper.createDocument();
2.创建元素的根节点
Element root = document.addElement("root");
3.根节点添加元素和属性
root.addElement("author").addAttribute("name","maomao").addAttribute("location","CN").addText("shenzhen" );
4.保存文件
writer.write(document);
writer.close();
例:
public static void main(String[] args) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter("test.xml"), format);
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
root.addComment("This is xml comment");
root.addElement("author").addAttribute("name", "maomao").addAttribute("location", "CN").addText("shenzhen");
writer.write(document);
writer.close();
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


