c# - 从 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();
}
解决方案
我从方法中删除了不相关的代码,只留下准确回答问题的代码。
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();
}
}
推荐阅读
- flutter - 错误三元运算符不在颤振中工作
- java - Marathon OSS:如何在 JAVA Swing GUI 上检查元素
- babylonjs - Babylon.js 中世界原点的中心网格
- kubernetes - minikube:如何将第二个容器添加到 pod?
- apache-flink - FlinkSQL:如何过滤掉 SQL 中格式错误的 JSON?
- datetime - pytz 增加额外的时间
- python - 如何使用 wheelEvent 将调整大小的 QGraphicPixmap 放置到 QGraphicsScene 中,同时保持光标下的相同像素
- python - 用于删除 python 注释的正则表达式
- vue.js - 无法在 Visual Studio 代码中导入 js 文件
- amazon-web-services - 如何格式化我的 boto3 lambda 函数中的密钥以更新 dynamodb?