java DOM解析XML

xml代码

<?xml version="1.0" encoding="UTF-8"?>


<configuration>
  
    <property location="remote">
        <url>jdbc:mysql://192.168.1.102:3306/test_orders</url>
        <name>test1</name>
        <password>123456</password>
    </property>
    
    <property location="local">
        <url>jdbc:mysql://192.168.1.103:3306/test_orders</url>
        <name>test2</name>
        <password>123456</password>
    </property>

</configuration>
java 代码

package testxml;

import java.io.File;
import java.util.HashMap;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class TestXML {

	public static void main(String[] args) {
		
		String filePath="/home/jpan/Mywork/configure.xml";
		File xmlFile = new File(filePath);
		if (!xmlFile.exists()) {
			System.out.println(filePath + " does not existed!");
		}

		try {
			
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document doc = builder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			System.out.println("Root  element: "+doc.getDocumentElement().getNodeName()); 
			NodeList nList = doc.getElementsByTagName("property");
			
			HashMap<String, String> map= new HashMap<>();
			
			for (int i = 0; i < nList.getLength(); i++) {
				Node node = nList.item(i);
				Element ele = (Element) node;

				if (ele.getAttribute("location").equals("remote")) {
					map.put("url", ele.getElementsByTagName("url").item(0).getTextContent());
					map.put("name", ele.getElementsByTagName("name").item(0).getTextContent());
					map.put("password", ele.getElementsByTagName("password").item(0).getTextContent());
					
				}
				else if(ele.getAttribute("location").equals("local")) {
					map.put("localurl", ele.getElementsByTagName("url").item(0).getTextContent());
					map.put("localname", ele.getElementsByTagName("name").item(0).getTextContent());
					map.put("localpassword", ele.getElementsByTagName("password").item(0).getTextContent());
					
				}
			}
			
			Set<String> keys = map.keySet();
			for (String s : keys) {
				System.out.println(s + "," + map.get(s));
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
学习XML解析,我认为可以把中间的每个变量都打印出来,这样有助于学习。我这个是为了读取数据库配置文件,写的比较烂,仅供参考。

java DOM 需要的jar包是xml-apis.jar

Maven代码

<dependency>
	<groupId>xml-apis</groupId>
	<artifactId>xml-apis</artifactId>
	<version>2.0.2</version>
</dependency>


你可能感兴趣的:(java,java,xml,Web,dom)