1. 程式人生 > >Java上傳且後臺解析XML檔案

Java上傳且後臺解析XML檔案

後臺程式碼:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 解析XML檔案
 * @author 【】
 *
 */
public class ReaderXML {

	@RequestMapping(value = "", method = RequestMethod.POST, produces = "text/plain;charset=utf-8")
	public void parseXML(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile mFile = multipartRequest.getFile("xml");
		// 獲取傳入的xml路徑
		String url = mFile.getOriginalFilename();
		// 獲取傳入的檔名稱
		String hzmc = mFile.getOriginalFilename().substring(mFile.getOriginalFilename().lastIndexOf("\\") + 1);
		// 解析XML檔案,返回節點資訊集合
		NodeList childNodes = getNodeLists(mFile);
		for (int i = 0; i < childNodes.getLength(); i++) {
			// 獲取單個節點資訊
			Node node = childNodes.item(i);
			if ("節點名".equals(node.getNodeName())) {
				String 節點值 = node.getTextContent();
				// 獲取該節點下子節點
				NodeList childNodes1 = node.getChildNodes();
			}
		}	
	}
	/*
	 * 解析XML檔案,返回節點資訊
	 */
	private NodeList getNodeLists(MultipartFile mFile) {
		// 讀取XML檔案內容
		BufferedReader br = new BufferedReader(new InputStreamReader(mFile.getInputStream(), "utf-8"));
		StringBuffer buffer = new StringBuffer();
		String line = " ";
		while ((line = br.readLine()) != null) {
			buffer.append(line);
		}
		InputStream stream = new ByteArrayInputStream(buffer.toString().getBytes());
		// 返回documentBuilderFactory物件
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		// 返回db物件用documentBuilderFatory物件獲得返回documentBuildr物件
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document document = db.parse(stream);
		Element element = document.getDocumentElement();
		NodeList childNodes = element.getChildNodes();
		
		return childNodes;
	}
}