简体   繁体   English

将 XmlWriter 转换为 Stream / char / byte []

[英]Convert XmlWriter to Stream / char / byte []

I have an asp.net/C#/Blazor environment, where a button generates an XML with a specific class.我有一个 asp.net/C#/Blazor 环境,其中一个按钮生成具有特定类的 XML。 With XML Writer, I can make the file, and even can save/download it, but it goes to the server-side (It must to be downloaded on client-side. please, do not argue about it).使用XML Writer,我可以制作文件,甚至可以保存/下载它,但它会转到服务器端(必须在客户端下载。请不要争论)。

I know Blazor implemented some instant download ( https://docs.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-6.0 ) and it works perfect with blank/new files, but the problem is, I don't know how to "pass" or convert my previously generated XML with XML Writer method, because Blazor method(s) only allow Stream, char or byte Arrays downloads.我知道 Blazor 实现了一些即时下载( https://docs.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-6.0 ),它适用于空白/新文件,但是问题是,我不知道如何使用 XML Writer 方法“传递”或转换我以前生成的 XML,因为 Blazor 方法只允许流、字符或字节数组下载。

When I tried to convert it, the error当我尝试转换它时,错误

Some of my code is:我的一些代码是:

    protected async Task CreateXmlFile(int correlativo,string idDocumento, string siglaDocumento, List<DocumentoXML> documentos = null, List<SignersXML> signersXMLs = null,
                                                                                                              List<ContentXMLComplemento> complementos = null,
                                                                                                              List<SignersXMLComplemento> signersComplemento = null)
{
    _xmlWriterSettings = new XmlWriterSettings
        {
            Indent = true,
            Encoding = new UTF8Encoding(false)
        };

    string fullPath= "";
    XmlWriter writer;
    XmlSerializer serializer;

        var documentoIngresoRaiz = new DocumentoIngresoRaiz
            {
                Content_XML = new List<ContentXML>
                {
                    new ContentXML
                    {
                        sve_XML = new List<sveXML>
                        {
                           new sveXML
                           {
                               Documento_XML = documentos
                           }
                        }
                    }
                },
                Signers_XML = signersXMLs
            };

        fullPath = $"{mainPath}Ingreso-{correlativo}.xml";
        var fileName = $"Ingreso-{correlativo}.xml";

        writer = XmlWriter.Create(fullPath, _xmlWriterSettings);
        serializer = new XmlSerializer(typeof(DocumentoIngresoRaiz));
        serializer.Serialize(writer, documentoIngresoRaiz);
        writer.Close(); 

    //I've been trying with these 3 Blazor method lines, to send my xml as stream
    var fileStream = new MemoryStream(writer);
    using var streamRef = new DotNetStreamReference(stream: fileStream);
    await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
}

Error CS1503: Argument 1: cannot convert from 'System.Xml.XmlWriter' to 'byte[]'错误 CS1503:参数 1:无法从 'System.Xml.XmlWriter' 转换为 'byte[]'

I've been looking all around StackOverflow and the Internet with no success.我一直在寻找 StackOverflow 和互联网,但没有成功。 I found some similar posts ( I want to download XML file in C# which I created using XmlWriter.Create() on user's system ) ( How to get a Stream from an XMLWriter? ), but they couldn't solve my problem.我发现了一些类似的帖子( 我想下载我在用户系统上使用 XmlWriter.Create() 创建的 C# 中的 XML 文件)( 如何从 XMLWriter 获取流? ),但他们无法解决我的问题。 Any help or tip is welcome.欢迎任何帮助或提示。 Thank you in advance!先感谢您!

Since there was no way to convert the already generated XML file to byte/stream/char array, I found out that the solution was:由于无法将已经生成的 XML 文件转换为 byte/stream/char 数组,我发现解决方案是:

saving this XML file on server-side and then immediately download it to local machine, via JavaScript code (pasted below), passing the fileURL (location of file on the server) and fileName (name of the file)将此 XML 文件保存在服务器端,然后立即通过 JavaScript 代码(粘贴在下面)将其下载到本地计算机,并传递 fileURL(服务器上文件的位置)和 fileName(文件名)

await JS.InvokeVoidAsync("triggerFileDownload", fileName, fileURL);
    
function triggerFileDownload(fileName, url) {
     const anchorElement = document.createElement('a');
     anchorElement.href = url;
     anchorElement.download = fileName ?? '';
     anchorElement.click();
     anchorElement.remove();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM