Código:
package com.facturas.servlets; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.w3c.dom.Element; import com.facturas.converters.ConverterEFACE; /** * Servlet implementation class FacturasG4S */ public class FacturasG4S extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public FacturasG4S() { // TODO Auto-generated constructor stub } private WebApplicationContext getContext() { ServletContext servletContext = this.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils. getRequiredWebApplicationContext(servletContext); return wac; } private String printDOM(Element xmlDoc) throws Exception { String retorno = ""; OutputFormat outputFormat = new OutputFormat("XML","UTF-8",true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLSerializer xmlSerializer = new XMLSerializer(baos, outputFormat); xmlSerializer.asDOMSerializer(); xmlSerializer.serialize(xmlDoc); System.out.println("Factura8: " + baos); File file = new File("c:\\archivo.xml"); if(baos != null) { retorno = baos.toString(); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(retorno); bw.close(); } return retorno; } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try { ConverterEFACE converter = (ConverterEFACE)getContext().getBean("converterEFACE"); String facturaId = request.getParameter("id"); if((facturaId != null) && (!facturaId.equals(""))) { Element elemento = converter.generateElement(Long.parseLong(facturaId)); response.getOutputStream().println(printDOM(elemento)); response.getOutputStream().close(); } } catch(Exception e) { e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }