后台代码:
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; } }