我可以使用CompactWriter()在XML(所有Newlines/Carriage返回)中删除PrettyPrint,但是如何保持我的序言和样式表?

目前,我正在使用Writer类使用Write方法添加Prolog和样式表。

以下是我序列化对象的功能。

private void serializeData(DiagData diagData){  
        fileinfo=new HashMap<String,String>();
        XStream xstream = new XStream();
        xstream.processAnnotations(DiagData.class);

        FileOutputStream fileOutputStream=null;
        Writer writer=null;
        //CompactWriter writer=null;
        xstream.registerConverter(new MapConverter());

        try {
            String path = Constants.XML_PATH+File.separator+Constants.DIRECTORY_NAME;
            File diagnosticDir = new File(path);

            String serialNumber=null;

            IDataCollector dataCollector=new DataCollector();
            serialNumber=dataCollector.getSerialNumber();

            String fileName = new SimpleDateFormat("yyyyMMddhhmmss'.xml'").format(new Date());
            if(serialNumber!=null)fileName=serialNumber+Constants.UNDERSCORE+fileName;
            fileName=Constants.PHONEHOME+Constants.UNDERSCORE+fileName;

            fileOutputStream = new FileOutputStream(path+File.separator+fileName);

            writer = new OutputStreamWriter(fileOutputStream);
            //writer = new CompactWriter(new OutputStreamWriter(fileOutputStream));

            writer.write(Constants.PROLOG);
            writer.write(Constants.STYLESHEET);
            xstream.toXML(diagData, writer);
            //xstream.marshal(diagData, writer);

        } catch (FileNotFoundException e1) {

        } catch (Exception e) {

        } finally {
            try {
                fileOutputStream.close();
                writer.close();             
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
        }
    }
有帮助吗?

解决方案

如果您看Xstream 文档, ,他们显然声明您必须自己添加XML Prolog:

Why does XStream not write an XML declaration?

XStream is designed to write XML snippets, so you can embed its output into 
an existing stream or string. You can write the XML declaration yourself into 
the Writer before using it to call XStream.toXML(writer).

以下代码应起作用。我删除了您的大部分代码,因此您必须将其放回原处。目的只是为您提供一个粗略的工作示例:

private static void serializeData(Object diagData) throws Exception {
    XStream xstream = new XStream();
    xstream.processAnnotations(DiagData.class);

    FileOutputStream fileOutputStream = null;
    Writer writer = new PrintWriter(new File(your file));
    CompactWriter compactWriter = new CompactWriter(writer);

    try {
        writer.write(your xml prolog);
        writer.write(your stylesheet);
        xstream.marshal(diagData, compactWriter);
    } catch (FileNotFoundException e1) {

    } catch (Exception e) {

    } finally {
       release resources
   }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top