简单的java读取xml文件方法(相对路径的xml文件),,分为两种: 一种是简单的键值对的xml文件, 通过Properties读取;一种是普通的xml文件, 此处使用dom4j读取
一.简单的键值对应的xml文件读取
1.xml文件 文件名(key-value-xml.xml)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <entry key="sql1"> Select sysdate From dual q </entry> <entry key="sql2"> Select 1 From dual q </entry> </properties>
2.java代码
public static void simpleKeyValueXmlRead(){ Properties props = new Properties(); //xml的相对路径 String xmlpath="com/meotd/service/key-value-xml.xml"; ClassLoader classLoader=XmlReadLearn.class.getClassLoader(); //这里XmlReadLearn是当前类 InputStream in=classLoader.getResourceAsStream(xmlpath); try { props.loadFromXML(in); System.out.println("按照Key打印"); System.out.println(props.getProperty("sql1")); //"sql1"是xml中某个entry的key值 System.out.println("打印所有的属性值"); Enumeration<Object> set2 = props.keys(); while (set2.hasMoreElements()) { String key = (String) set2.nextElement(); System.out.println(props.getProperty(key)); } } catch (Exception e) { e.printStackTrace(); } }
二.普通的xml文件读取(dom4j)
1.xml代码
<?xml version="1.0" encoding="UTF-8"?> <sqls> <sql id="attr-desc-data"> Select Distinct Tag_Name As Identifier, 'string' As Type, Tag_Name As Name, Tag_Name As Description, Null As Secondarydescription, 'CMS MIG' As Attributefield3, 'TRUE' As Displayable, 'TRUE' As Comparable, Decode(Secondary_Navigation, 0, 'FALSE', 1, 'TRUE') As Facetable From Cms_Tag Order By 1 </sql> <sql id="attrval-desc-data"> Select Tag_Name As Identifier, 'string' As Type, Tag_Value As ValueIdentifier, '1' As ValueUsage, 0 As sequence, tag_value As Value, Freetype_Id As field1 From Cms_Tag Order By Tag_Name </sql> </sqls>