product.xml:
<?xml version="1.0" encoding="UTF-8"?> <root> <product> <index id="1">交换机</index> <index id="2">传送网</index> <index id="3">WLAN</index> <index id="4">路由器</index> </product> <scene> <index id="1">规划</index> <index id="2">实施</index> <index id="3">维护</index> </scene> </root>
代码:
package com.cy.test; import java.io.File; import java.net.URLDecoder; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class ReadXmlFile { public static void main(String[] args) throws Exception{ String path = URLDecoder.decode(ReadXmlFile.class.getClassLoader().getResource("").getPath(), "UTF-8") + "product.xml"; SAXReader reader = new SAXReader(); Document document = reader.read(new File(path)); //获取文档的根节点 Element root = document.getRootElement(); //获取product的节点 Element element = root.element("product"); List<Element> proList = element.elements(); for(Element e: proList){ String value = e.getTextTrim(); Attribute attr = e.attribute("id"); String key = attr.getValue(); System.out.println("key:" + key + "--value:" +value); } //获取scene节点 Element sElement = root.element("scene"); List<Element> sList = sElement.elements(); for(Element e : sList){ String value = e.getTextTrim(); String key = e.attributeValue("id"); System.out.println("key:" + key + "----value:" + value); } //将xml转化为map Map<Integer, String> prodcutMap = xml2Map(path); for (Map.Entry<Integer, String> entry : prodcutMap.entrySet()) { System.out.println("键= " + entry.getKey() + " and 值= " + entry.getValue()); } } //将xml转化为map public static Map<Integer, String> xml2Map(String path) throws Exception{ Map<Integer, String> productMap = new HashMap<Integer, String>(); Document document = new SAXReader().read(path); Element root = document.getRootElement(); //获取根节点 Iterator<Element> it = root.element("product").elementIterator(); //获取根节点下的子节点product下面的所有节点 while(it.hasNext()){ Element e = (Element) it.next(); Integer key = Integer.parseInt(e.attributeValue("id")); String value = e.getTextTrim(); productMap.put(key, value); } return productMap; } }
//可以将上面xml2Map改装,传入节点名字,nodeName,然后输出map
console:
时间: 2024-10-12 22:21:26