Staxmate API的缩进问题

时间:2010-07-14 14:47:20

标签: java xml xml-serialization stax staxmate

我正在使用Staxmate API生成XML文件。阅读完教程后:http://staxmate.codehaus.org/Tutorial我尝试在代码中进行更改。最后我添加了电话

doc.setIndentation("\n  ", 1, 1);

这导致新生成的XML文件为空!如果没有此方法,则会按预期生成整个XML文件。

在项目设置中怀疑有些东西,我使用教程中给出的代码在同一个包中创建了一个Test类:

package ch.synlogic.iaf.export;

import java.io.File;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;

import org.codehaus.staxmate.SMOutputFactory;
import org.codehaus.staxmate.out.SMOutputDocument;
import org.codehaus.staxmate.out.SMOutputElement;

public class Test {

public static void main(String[] args) {
 main("c:\\tmp\\empl.xml");
}

public static void main(String fname)
{
 // 1: need output factory
 SMOutputFactory outf = new SMOutputFactory(XMLOutputFactory.newInstance());
 SMOutputDocument doc;
 try {
  doc = outf.createOutputDocument(new File(fname));

 // (optional) 3: enable indentation (note spaces after backslash!)
 doc.setIndentation("\n  ", 1, 1);
 // 4. comment regarding generation time
 doc.addComment(" generated: "+new java.util.Date().toString());
 SMOutputElement empl = doc.addElement("employee");
 empl.addAttribute(/*namespace*/ null, "id", 123);
 SMOutputElement name = empl.addElement("name");
 name.addElement("first").addCharacters("Tatu");
 name.addElement("last").addCharacters("Saloranta");
 // 10. close the document to close elements, flush output
 doc.closeRoot();
 } catch (XMLStreamException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}
}

现在当我从我的代码中调用main(String)方法时,问题仍然存在,而如果我只是运行类Test,它就会顺利运行!我的代码涉及数据库初始化和一些其他产品特定的操作。

我迷失了,对于我该如何处理这个想法?

2 个答案:

答案 0 :(得分:1)

缩进适用于Woodstox API

WstxOutputFactory factory = new WstxOutputFactory();
factory.setProperty(WstxOutputFactory.P_AUTOMATIC_EMPTY_ELEMENTS, true);
SMOutputFactory outf = new SMOutputFactory(factory);
doc = outf.createOutputDocument(fout);
doc.setIndentation("\n  ", 1, 1);

答案 1 :(得分:1)

以下对我有用 - context.setIndentation(“\ r \ n \ t \ t \ t \ t \ t \ t \ t \ t \ t \ t”,2,1); //每个级别的窗口lf和1个标签缩进

相关问题