dom4j的使用
2024/4/9...小于 1 分钟
dom4j的简单使用
引入依赖
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
编写配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<companys>
<company id="1770294182066073601">
<product id="1773321675404529665">
<bom bomId="1773321675404529665" edgePlatformKey="bom1"></bom>
<bom bomId="1773321675404529665" edgePlatformKey="bom2"></bom>
<bom bomId="1773321675404529665" edgePlatformKey="bom3"></bom>
</product>
<product id="1773321675404529662">
<bom bomId="1773321675404529663" edgePlatformKey="bom1"></bom>
<bom bomId="1773321675404529664" edgePlatformKey="bom2"></bom>
<bom bomId="1773321675404529665" edgePlatformKey="bom3"></bom>
</product>
</company>
</companys>
Springboot的Test使用
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ApsApplication.class})
public class TestRedis {
@Test
public void Test2() {
Map<Long, Map<Long, Map<Long, String>>> companyBomMap = new HashMap<>();
// 1. 创建SAXReader对象
SAXReader reader = new SAXReader();
ClassPathResource classPathResource = new ClassPathResource("CompanyProductWithBom.xml");
try (InputStream inputStream = classPathResource.getInputStream()){
Document read = reader.read(inputStream);
// 2. 解析根
Element rootElement = read.getRootElement();
Iterator<Element> iterator = rootElement.elementIterator();
while (iterator.hasNext()) {
Map<Long, Map<Long, String>> productBom = new HashMap<>();
Element companyBomList = iterator.next();
// 3. 取属性
Long companyId = Long.parseLong(companyBomList.attribute("id").getValue());
// 4. 解析产品列表
Iterator<Element> productIterator = companyBomList.elementIterator("product");
while (productIterator.hasNext()) {
Map<Long, String> bomMap = new HashMap<>();
Element productList = productIterator.next();
// 5. 取属性
Long productId = Long.parseLong(productList.attribute("id").getValue());
// 6. 解析BOM列表
Iterator<Element> bomIterator = productList.elementIterator("bom");
while (bomIterator.hasNext()) {
Element bom = bomIterator.next();
String edgePlatformKey = bom.attribute("edgePlatformKey").getValue();
bomMap.put(Long.parseLong(bom.attribute("bomId").getValue()), edgePlatformKey);
productBom.put(productId, bomMap);
}
}
companyBomMap.put(companyId, productBom);
}
} catch (IOException | DocumentException e) {
log.error("没有解析到配置文件", e);
throw new ServiceException(ErrorCodeEnum.NOT_CONFIG_FILE);
}
}
}