/**
* 加载配置文件节点
*
* @param attributeValue 节点属性值
* @param age节点属性值
* @date 2023-12-08
*/
public static Map<String,String> getConfigXml(String attributeValue,String age){
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[@age='"+age+"']");
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="Employee">
<item age="99">
<dsecribe>人员数量</dsecribe>
<count>5</count>
</item>
<item age="100">
<dsecribe>人员数量</dsecribe>
<count>5</count>
</item>
</project>
<!--这个节点要通过改变定位表达式来获取-->
<project val="AreaRelevance">
<item>
<regionArea>72</regionArea>
<SArea>31,32,33,34,96</SArea>
</item>
</project>
</body>