* 加载配置文件节点 * @param attributeValue 节点属性值 * @param areaCode 节点属性值 */ public static Map<String,String> getConfigXml(String attributeValue,String areaCode){ String filePath="config.xml"; Map<String,String> resultMap=new HashMap<>(); try{ File xmlFile=new File(filePath); // 创建DocumentBuilderFactory和DocumentBuilder DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); // 使用DocumentBuilder解析XML文件 Document doc=dBuilder.parse(xmlFile); // 创建XPath对象 XPathFactory xPathFactory=XPathFactory.newInstance(); XPath xpath=xPathFactory.newXPath(); // 使用XPath 表达式定位节点 XPathExpression expr=xpath.compile("//project[@val='"+attributeValue+"']/item[@areacode='"+areaCode+"']"); resultMap=parseItemsWithAttribute(doc,expr); System.out.println(resultMap); System.out.println("count: "+resultMap.get("count")); }catch(Exception e){ e.printStackTrace(); throw new ServiceException("getConfigXml方法异常"); } return resultMap; } * 加载xml,并返回map集合 * * @param doc 解析的xml * @param expr 节点定位表达式 * @author wyj * @date 2023-12-08 */ private static Map<String,String> parseItemsWithAttribute(Document doc,XPathExpression expr){ Map<String,String> resultMap=new HashMap<>(); try{ // 获取匹配的节点 Node itemNodes=(Node)expr.evaluate(doc,XPathConstants.NODE); //获取节点下的子节点 NodeList childNodes=itemNodes.getChildNodes(); // 遍历节点列表并获取子节点的值 for(int i=0;i<childNodes.getLength();i++){ Node childNode=childNodes.item(i); if(childNode.getNodeType()==Node.ELEMENT_NODE){ String childNodeName=childNode.getNodeName(); String childNodeValue=childNode.getTextContent(); resultMap.put(childNodeName,childNodeValue); } } }catch(XPathExpressionException e){ e.printStackTrace(); throw new ServiceException("parseItemsWithAttribute方法异常"); } return resultMap; }
自定义XML <?xml version="1.0" encoding="utf-8"?> <body> <project val="one"> <item areacode="72"> <dsecribe>测试</dsecribe> <count>5</count> </item> <item areacode="42"> <dsecribe>测试2</dsecribe> <count>5</count> </item> </project> <!--这个节点要通过改变定位表达式来获取--> <project val="AreaRelevance"> <item> <regionArea>72</regionArea> <ShengArea>31,32,33,34,35,36</ShengArea> </item> </project> </body>
标签:XPath,Java,自定义,expr,resultMap,param,doc,节点 From: https://www.cnblogs.com/WuUranus/p/18006420