• 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;
    	}
    }
    
  • 相关阅读:
    由二进制移位想到的
    KDJ指标详解
    PMP考试结束
    转K线理论初级二
    日本地震效应
    Baseline之流水先生的见解
    KDJ判断原则
    转K线理论初级一
    管理学法则
    今天提到KW,特此@Mark一下
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/9915502.html
Copyright © 2020-2023  润新知