【JAVA】Java 使用 XPath表达式定位节点读取自定义XML方法

     * 加载配置文件节点
     * @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>

  

posted @ 2024-02-04 16:00  喝了烫嘴的水  阅读(140)  评论(0编辑  收藏  举报