zoukankan      html  css  js  c++  java
  • java如何解析xml?

    技术点: getResourceAsStream方法,dom4j的SaxReader解析xml

    1.加载磁盘xml文件到内存中(InputStream)

    package com.example.utils;
     
    import java.io.InputStream;
     
    public class Resource {
        public static InputStream load(String path) {
            return Resource.class.getClassLoader().getResourceAsStream(path);
        }
    }

    2.引入dom4j的jar依赖包

        <dependencies>
            <dependency>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
                <version>1.6.1</version>
            </dependency>
        </dependencies>

    3.使用SaxReader类解析xml的内存输入流InputStream

        public Properties parse(InputStream in) throws DocumentException {
            Properties prop = new Properties();
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(in);
            Element rootElement = document.getRootElement();
            List<Element> list = rootElement.selectNodes("//property");
            for (Element element : list) {
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                prop.setProperty(name, value);
            }
            return prop;
        }
  • 相关阅读:
    Django model 常用方法记录
    程序员的注意事项
    硬件天使的使用
    你是否应该成为一名全栈工程师?
    web技术
    6个处理上面代码异味的重构方法(手法)
    git 命定
    ie console报错
    apache 省略index.php访问
    myisam和innodb的区别
  • 原文地址:https://www.cnblogs.com/powerbear/p/15155956.html
Copyright © 2011-2022 走看看