当前位置: 首页 > news >正文

解析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

 

http://www.lryc.cn/news/119256.html

相关文章:

  • JavaScript基础 第三天
  • 2.Redis部署到Windows服务器
  • 【修正-高斯拉普拉斯滤波器-用于平滑和去噪】基于修正高斯滤波拉普拉斯地震到达时间自动检测研究(Matlab代码实现)
  • Go语言基础: 有参函数Func、Map、Strings详细案例教程
  • JDBC连接数据库如何实现你会吗???
  • C#与C++交互(2)——ANSI、UTF8、Unicode文本编码
  • SQLSTATE[42000]: this is incompatible with sql_mode=only_full_group_by in
  • 企业权限管理(五)-订单分页
  • Blender如何给fbx模型添加材质贴图并导出带有材质贴图的模型
  • MySQL不走索引的情况分析
  • 安装ubuntu22.04系统,配置国内源以及ssh远程登录
  • win10 安装ubuntu子系统并安装宝塔
  • gazebo 导入从blender导出的dae等文件
  • 目标检测YOLOv3基于DarkNet53模型测试-笔记
  • Unity项目中查找所有使用某一张图片的材质球,再查找所有使用材质球的预设
  • postman接口测试中文汉化教程
  • java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver的解决办法
  • 认识所有权
  • 恒盛策略:怎样看k线图实图详解如何看懂k线图?
  • 物联网的定义、原理、示例、未来
  • Vue 整合 Element UI 、路由嵌套和参数传递(五)
  • Git全栈体系(四)
  • 数据结构初阶--二叉树的链式结构
  • Taro UI中的AtTabs
  • ChatGPT FAQ指南
  • 在矩池云使用ChatGLM-6B ChatGLM2-6B
  • 7.2 手撕VGG11模型 使用Fashion_mnist数据训练VGG
  • docker安装ES
  • python爬虫实战(2)--爬取某博热搜数据
  • k8s的Namespace详解