import org.apache.commons.lang3.StringUtils; import org.dom4j.*; import org.dom4j.io.SAXReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * 文本解析 */ public class XmlHelper { static Logger logger = LoggerFactory.getLogger(XmlHelper.class); /** * 通过文字读取资源文件 * @param str 读取字符 * @return */ public static Element getRootElementByStr(String str) { SAXReader reader = new SAXReader(); Element element = null; try { Document document = reader.read(new InputStreamReader(new ByteArrayInputStream(str.getBytes()))); element = document.getRootElement(); } catch (DocumentException e) { e.getMessage(); logger.error(e.getMessage()); } return element; } /** * 通过 path 读取资源文件 * @param path 资源路径 * @return */ public static Element getRootElementByPath(String path) { Element root = null; try { SAXReader reader = new SAXReader(); Document document = reader.read(path); root = document.getRootElement(); } catch (DocumentException e) { e.getMessage(); logger.error(e.getMessage()); } return root; } /** * 通过 资源文件路径 读取资源文件 * @param path \\a\\b\\c.text * @return */ public static Element getRootElementByResourcePath(String path) throws IOException { if(StringUtils.isEmpty(path)){ return null; } Element root = null; try{ ClassPathResource classPathResource = new ClassPathResource(path); root = XmlHelper.getRootElementByIO(classPathResource.getInputStream()); }catch (Exception e){ e.getMessage(); logger.error(e.getMessage()); } return root; } /** * 通过 IO 流读取 * @param inputStream * @return */ public static Element getRootElementByIO(InputStream inputStream) { Element root = null; try { SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); root = document.getRootElement(); } catch (DocumentException e) { e.getMessage(); logger.error(e.getMessage()); } return root; } /** * 解析dom * @param rootNode * @param name * @return */ public static List<Element> getXmlElemets(Element rootNode, String name) { if (rootNode == null && name == "") { return null; } return rootNode.elements(name); } }
xml解析工具类
最新推荐文章于 2024-05-27 09:57:41 发布