1、解析方法
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public static Map<String, String> parseXml(String xmlPath) { /** * 以解析xml中的dataSource标签中的url username password属性值为例 */ String url = ""; String username = ""; String password = ""; Map<String, String> map = new HashMap<String, String>(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); /** * xmlPath为待解析xml文件的路径 */ Document document = db.parse(xmlPath); /** * 此处的dataSource为标签名,即获取该xml文件下所有的dataSource标签 */ NodeList nodeList = document.getElementsByTagName("dataSource"); /** * 遍历标签(xml文件内dataSorce标签只有一个) */ for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); /** * 获取item标签的属性字段 */ NamedNodeMap attributes = item.getAttributes(); /** * 遍历该标签的所有属性 */ for (int j = 0; j < attributes.getLength(); j++) { /** * 此处就是获取指定属性的值 */ if ("dbUrl".equals(attributes.item(j).getNodeName())) { url = attributes.item(j).getNodeValue(); } else if ("userName".equals(attributes.item(j).getNodeName())) { username = attributes.item(j).getNodeValue(); } else if ("passWord".equals(attributes.item(j).getNodeName())) { password = attributes.item(j).getNodeValue(); } } } map.put("url", url); map.put("username", username); map.put("password", password); } catch (Exception e) { e.printStackTrace(); } return map; }
2、测试xml的内容
<?xml version="1.0" encoding="gbk"?> <config> <dataSource name="default" desc="彩票数据源" driverName="com.mysql.jdbc.Driver" dbUrl="jdbc:mysql://localhost:3306/icaipiao?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true" userName="root" passWord="123456" checkSql="select 1+2 FROM dual" interval="1" startNum="2" maxNum="10" maxCallNum="100000" serverType="mysql" dbUrlBak=""> </dataSource> <map file="C://1.txt"></map> </config>
标签:Xml,xml,Java,配置文件,map,标签,item,import,attributes From: https://www.cnblogs.com/sun-10387834/p/17853733.html