반응형
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
@RequestMapping("upload")
	public ModelAndView upload(HttpServletResponse response, @RequestParam("file") MultipartFile file) {

		ModelAndView mv = new ModelAndView("dispxml");
		if (!file.isEmpty()) {
			try {

				response.setContentType("text/xml");
				File inputFile = new File(file.getOriginalFilename());
				file.transferTo(inputFile);
				
				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				Document doc = dBuilder.parse(inputFile);
				dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
				doc.getDocumentElement().normalize();
				OutputFormat format = new OutputFormat(doc);
				String filename = "mydocument" + System.currentTimeMillis() + ".xml";
				
				@SuppressWarnings("deprecation")
				XMLSerializer serialize = new XMLSerializer(new FileOutputStream(new File(filename)), format);
				TransformerFactory tf = TransformerFactory.newInstance();
				Transformer transformer = tf.newTransformer();
				transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				StringWriter writer = new StringWriter();
				transformer.transform(new DOMSource(doc), new StreamResult(writer));
				String output = writer.getBuffer().toString().replaceAll("\r", "");
				System.out.println(output);
				mv.addObject("file", output);
				response.setContentType("text/xml");

				return mv;

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		return null;

	}
		<dependency>
		    <groupId>xml-apis</groupId>
		    <artifactId>xml-apis</artifactId>
		    <version>2.0.2</version>
		</dependency>

출처 : http://blog.naver.com/PostView.nhn?blogId=skinfosec2000&logNo=220707575523

728x90

+ Recent posts