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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值