【问题标题】:Generate and Download XML生成和下载 XML
【发布时间】:2016-07-27 16:30:14
【问题描述】:

我正在尝试从一些数据生成 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 转换为字符串。

【问题讨论】:

    标签: xml primefaces download


    【解决方案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");
    

    【讨论】:

    猜你喜欢
    • 2019-09-12
    • 1970-01-01
    • 2013-05-07
    • 2019-05-25
    • 2015-10-01
    • 2014-12-17
    • 2018-12-31
    • 2020-01-25
    • 2012-10-13
    相关资源
    最近更新 更多