欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

dom4j格式化xml文件

程序员文章站 2022-04-13 22:16:56
...
[b]dom4j格式xml并输出为*.xml文件[/b]
public static void main(String[] args) {   
Document document = DocumentHelper.createDocument();
Element employees=document.addElement("employees");
Element employee=employees.addElement("employee");
Element name= employee.addElement("name");
name.setText("jim");
Element sex=employee.addElement("sex");
sex.setText("male");
Element age=employee.addElement("age");
age.setText("29");
try {
OutputFormat format = new OutputFormat();
format.setIndent(true);
format.setNewlines(true);
Writer fileWriter=new FileWriter("F:/test.xml");
XMLWriter xmlWriter=new XMLWriter(fileWriter,format);
xmlWriter.write(document);
xmlWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

[b]dom4j格式化xml并格式化输出[/b]
public static String formatXml(String str) throws DocumentException, IOException {
SAXReader reader=new SAXReader();
StringReader in=new StringReader(str);
Document doc=reader.read(in);
OutputFormat formater=OutputFormat.createPrettyPrint();
formater.setEncoding("UTF-8");
StringWriter out=new StringWriter();
XMLWriter writer=new XMLWriter(out,formater);
writer.write(doc);
writer.close();
return out.toString();
}
相关标签: dom4j