解析xml文件,获取需要的数据并写入txt文件中
=_= 话不多说!直接上代码!=_=
1、XmlUtil.java xml解析工具类
public class XmlUtil {private static String dicName = "";private static String dicValue = "";// 用于存储需要的数据private static List<Map<String, String>> paramlist = new ArrayList();/*** 找到所有xml文件,并进行解析* @param strPath 文件路径* @param name 检索的属性名称* @param value 检索的属性值* @throws Exception*/public static void refreshFileList(String strPath, String name, String value){// 设置需要检索的值dicName = name;dicValue = value;// 创建文件对象File dir = new File(strPath);File[] files = dir.listFiles();if (files == null) {return;}// 遍历当前目录下所有的文件和文件夹for (int i = 0; i < files.length; i++) {if (files[i].isDirectory()) { // 文件夹refreshFileList(files[i].getAbsolutePath(), name, value);} else { // 文件// 判断是否为xml文件if (files[i].getAbsoluteFile().getName().split("\\.")[1].equals("xml")) {// 解析xml文件parseFile(files[i].getAbsoluteFile());}}}}/*** 将xml文件解析成Document对象* @param filePath*/public static void parseFile(File filePath) {// 1.创建DocumentBuilderFactory对象DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();try {// 2.创建DocumentBuilder对象DocumentBuilder builder = factory.newDocumentBuilder();// 3.将xml文件解析成Document对象Document document = builder.parse(filePath);// 4.获取根节点 model:Model为标签名称NodeList sList = document.getElementsByTagName("model:Model");// 5.通过Element方式解析并获取使用字典的字段Map<String, String> parMap = element(sList);// 6.存入需要的数据if (!parMap.isEmpty()) {paramlist.add(parMap);}} catch (Exception e) {e.printStackTrace();}}/*** 用Element方式获取节点信息以及所有属性信息* @param list*/public static Map<String, String> element(NodeList list) {Map<String, String> parMap = new HashMap<>();for (int i = 0; i < list.getLength(); i++) {Element element = (Element) list.item(i);// 获取所有attribute标签NodeList attribute = element.getElementsByTagName("attribute");for (int j = 0; j < attribute.getLength(); j++) {// 判断是否有属性if (attribute.item(j).hasAttributes()) {Map<String, String> map = new HashMap<>();// 存在则获取所有的属性NamedNodeMap attributes = attribute.item(j).getAttributes();for (int k = 0; k < attributes.getLength(); k++) {// 属性名String nodeName = attributes.item(k).getNodeName();// 属性值String nodeValue = attributes.item(k).getNodeValue();// 拿到属性名称和属性值if ("name".equals(nodeName)) {map.put("name", nodeValue);}if ("value".equals(nodeName)) {map.put("value", nodeValue);}}// 判断是否使用的院系字典if (dicName.equals(map.get("name")) && dicValue.equals(map.get("value"))) {// 获取使用了字典的字段Node parentNode = attribute.item(j).getParentNode();if (parentNode.hasAttributes()) {// 所有的属性NamedNodeMap attributes1 = parentNode.getAttributes();for (int l = 0; l < attributes1.getLength(); l++) {parMap.put(attributes1.item(l).getNodeName(), attributes1.item(l).getNodeValue());}}// 文件路径存入parMap.put("url", parentNode.getOwnerDocument().getDocumentURI());}map.clear();}}}return parMap;}/*** 讲数据写入txt文件中* @param writePath 写入的路径* @throws Exception*/public void writeData(String writePath) throws Exception {// 拼接内容StringBuffer stringBuffer = new StringBuffer();paramlist.forEach(e -> {stringBuffer.append(e.get("url") + " ======= " + e.get("caption") + " ======= " + e.get("name") + "\n");});File file = new File(writePath);File parentFile = file.getParentFile();// 文件夹不存在,创建文件夹if (!parentFile.exists()) {parentFile.mkdirs();}// 创建文件file.createNewFile();FileOutputStream fileOutputStream = new FileOutputStream(file);BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream));// 写入数据writer.write(String.valueOf(stringBuffer));writer.close();System.out.println("文件写入完毕");}
}
2、测试代码
public static void main(String[] args) throws Exception {long a = System.currentTimeMillis();XmlUtil xmlUtil = new XmlUtil();// 设置需要检索的属性名和值xmlUtil.refreshFileList("D:\\my\\file_test", "dic", "d-b122-sad-2d3q-12");xmlUtil.writeData("D:\\my\\outfile\\file1.txt");System.out.println("消耗时长:" + (System.currentTimeMillis() - a));}
解析xml方式还有很多种,这只是其中一种,可以参考:Java XML解析 - 利用dom(org.w3c.dom)解析XML