0

I am attempting to generate an XML file from some data, and then download the file using PrimeFaces but I cannot put all the pieces together to accomplish this.

My code for generating the xml file is below:

        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);

I have left out the method call for "buildRoutePath", but this just generates the xml.

How do I take this generated xml file and download it using PrimeFaces file download? http://primefaces.org/showcase/ui/file/download.xhtml

I can see using this link that it is possible, but I would prefer to use the file, and not convert the XML to a string.

Community
  • 1
  • 1
Tony Scialo
  • 5,457
  • 11
  • 35
  • 52

1 Answers1

1

There is no need to stream your xml to file after transformation. You can just use byte buffer.

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");
Aleksandr Erokhin
  • 1,904
  • 3
  • 17
  • 32
  • I used this answer in combination with the answer provided by BalusC to handle the NotSerializableException i was getting http://stackoverflow.com/questions/20518363/notserializableexception-in-viewscop-bean-in-jsf?answertab=votes#tab-top – Tony Scialo Jul 27 '16 at 21:55