java生成XML文件自动换行问题,在哪里修改?
// 写入xml文件
public static void callWriteXmlFile(Document doc, Writer w,
String encoding) {
try {
Source source = new DOMSource(doc);
Result result = new StreamResult(w);
Transformer xformer = TransformerFactory.newInstance()
.newTransformer();
xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
xformer.transform(source, result);
XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
}
catch (Transformer
ConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
e.printStackTrace();
}
}
public void writeXMLFile(String outfile)
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
try
{
builder = dbf.newDocumentBuilder();
}
catch(Exception e){}
Document doc = builder.newDocument();
Element root = doc.createElement("商务区花名册");
doc.appendChild(root); //将根元素添加到文档上
//获取警务区信息
for(int i=0;i<jingwu_Vector.size();i++)
{
Qu s = (Qu)jingwu_Vector.get(i);
//创建一个商务区
Element stu = doc.createElement("警务区");
if(s.getRem()==null) s.setRem("");
stu.setAttribute("id",s.getNameno()+s.getRem());
//System.out.println(s.getNameno()+s.getRem());
root.appendChild(stu);//添加属性
//创建日期节点
Element name = doc.createElement("日期");
stu.appendChild(name);
Text tname = doc.createTextNode(s.getAcdate());
name.appendChild(tname);
//if(s.getHis()>0) {
Element age = doc.createElement("历史");
stu.appendChild(age);
Text tage = doc.createTextNode(String.valueOf(s.getHis()));
age.appendChild(tage);
}
try {
FileOutputStream fos = new FileOutputStream(outfile);
OutputStreamWriter outwriter = new OutputStreamWriter(fos);
//((XmlDocument)doc).write(outwriter); //出错!
callWriteXmlFile(doc,outwriter,"gb2312");
outwriter.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
writeXMLFile用来生成XML,但XML在记事本中不会自动换行,如何修改才能使其自动换行?
------解决方案--------------------
对不起应该是
Java code
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty(""{http://xml.apache.org/xslt}indent-amount"", "4");