2016-07-27 64 views
0

我试图从一些数据生成一个XML文件,然后使用PrimeFaces下载文件,但我无法将所有这些文件放在一起来完成此操作。生成并下载XML

我生成XML文件代码如下:

 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 

     Document doc = docBuilder.newDocument(); 
     Element rootElement = doc.createElement("RoutePaths"); 
     doc.appendChild(rootElement); 

     Attr attribute = doc.createAttribute("xmlns"); 
     attribute.setValue("http://tempuri.org/RoutePath.xsd"); 
     rootElement.setAttributeNode(attribute); 

     for(RssmXml record : xmlList) 
      rootElement.appendChild(buildRoutePath(doc,record)); 

     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     Transformer transformer = transformerFactory.newTransformer(); 
     DOMSource source = new DOMSource(doc); 

     StreamResult result = new StreamResult(new File("someFile.xml")); 
     transformer.transform(source, result); 

我已经离开了该方法调用“buildRoutePath”,但这只是生成XML。

如何使用此生成的xml文件并使用PrimeFaces文件下载进行下载?http://primefaces.org/showcase/ui/file/download.xhtml

我可以看到使用此link,这是可能的,但我更喜欢使用该文件,而不是将XML转换为字符串。

回答

1

转换后不需要将xml文件串流到文件。你可以使用字节缓冲区。

ByteArrayOutputStream out = new ByteArrayOutputStream(); 
transformer.transform(source, new StreamResult(out)); 
InputStream in = new ByteArrayInputStream(out.toByteArray()); 
StreamedContent file = new DefaultStreamedContent(in, "application/xml", "file.xml"); 
+0

我用这个答案结合由BalusC提供的答案来处理我居然也得到了NotSerializableException http://stackoverflow.com/questions/20518363/notserializableexception-in-viewscop-bean-in-jsf?answertab =票#制表顶 –