生成并下载XML

时间:2016-07-27 16:30:14

标签: xml primefaces download

我正在尝试从某些数据生成XML文件,然后使用PrimeFaces下载该文件,但我无法将所有部分放在一起来完成此任务。

我生成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 个答案:

答案 0 :(得分: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");