首页 > 解决方案 > 从 C# XML 函数返回字节 []

问题描述

此函数使用 XSL 将 XML 转换为 HTML。我需要保存在内存中创建的 HTML 以供以后使用

public void CreateHtml(string xmlRoute, string xlsRoute)
    {
        ByteArrayOutputStream bote = new ByteArrayOutputStream();
        // Cargamos la hoja de estilo que utilizaremos
        XslTransform xslt = new XslTransform();
        xslt.Load(xlsRoute);
        //Carga el archivo que deseamos transformar.
        XPathDocument doc = new XPathDocument(xmlRoute);
        //Instanciamos XmlTextWriter con una consola de salida.
        XmlWriter writer = new XmlTextWriter(Console.Out);
        xslt.Transform(doc, null, writer, null);
        writer.Close();
        //Declarar y crear un nuevo objeto XslCompiledTransform
        XslCompiledTransform transform = new XslCompiledTransform();
        //Cargamos el Xls que utilizaremos
        transform.Load(xlsRoute);
        //Generamos nuestro Html
        transform.Transform(xmlRoute, "Prueba002.pdf");
    }

目的是将函数类型更改为 byte[] 并将 html 作为 byteArray 返回。我基于这个Java代码

public byte[] createHtml(String xmlPath, String xslPath) throws IOException, TransformerException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(baos);
    StreamSource xml = new StreamSource(new File(xmlPath));
    StreamSource xsl = new StreamSource(new File(xslPath));
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xsl);
    transformer.transform(xml, new StreamResult(writer));
    writer.flush();
    writer.close();
    return baos.toByteArray();
}

标签: c#function

解决方案


我从方法中删除了不相关的代码,只留下准确回答问题的代码。

public byte[] CreateHtml(string xmlRoute, string xlsRoute)
{
    var xslt = new XslCompiledTransform();
    xslt.Load(xlsRoute);

    using (var stream = new MemoryStream())
    using (var writer = XmlWriter.Create(stream))
    {
        xslt.Transform(xmlRoute, writer);

        return stream.ToArray();
    }
}

推荐阅读