有xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<application>
<!-- 网络配置-->
<module name="Http">
<group name="FileUpload">
<configValue key="TempDir">D:\\temp\\upload\\</configValue>
<configValue key="MaxSize">104857600</configValue>
<configValue key="Include">txt,png</configValue>
</module>
</application>
别人的读取:
public class Dom4jReadXml {
public static void main(String[] args) {
readXml();
}
public static void readXml(){
try {
// 创建SAXReader对象
SAXReader reader = new SAXReader();
// 加载xml文件
Document dc= reader.read(new File("books.xml"));
// 获取根节点
Element e = dc.getRootElement();
// 获取迭代器
Iterator it = e.elementIterator();
// 遍历迭代器,获取根节点信息
while(it.hasNext()){
Element book = (Element) it.next();
List<Attribute> atts= book.attributes();
// 获取book属性名和属性值
for (Attribute att : atts) {
System.out.println("节点名:"+att.getName()+"节点值:"+att.getValue());
}
Iterator itt = book.elementIterator();
while(itt.hasNext()){
Element b = (Element) itt.next();
System.out.println("属性名:"+b.getName()+"属性值:"+b.getText());
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
方法挺好,就是我拿不到我要的东西
我写的方法:
/**
* 根据一二三级字节点的key,迭代到第三级节点根据三级key获取值
* <!-- 网络配置-->
* <module name="Http">
* <group name="FileUpload">
* <configValue key="TempDir">D:\\temp\\upload\\</configValue>
* </group>
* </module>
*
* @param key1
* @param key2
* @param key3
* @return
* @author banxian
* @date: 2021/1/21 19:51
*/
public String getXmlValue(String key1, String key2, String key3) {
try {
//1.创建Reader对象
SAXReader reader = new SAXReader();
//2.加载xml
String directoryPath = Thread.currentThread().getContextClassLoader().getResource("config.xml").getPath();//获取项目根目录
Document document = reader.read(new File(directoryPath));
//3.获取根节点
Element rootElement = document.getRootElement();
Element moduleElement = getTargetElement(key1, rootElement);
Element groupElement = getTargetElement(key2, moduleElement);
Element configElement = getTargetElement(key3, groupElement);
Attribute attribute = (Attribute) configElement.attributes().get(0);
String key = attribute.getValue();
Text text3 = (Text) configElement.content().get(0);
String value = text3.getText();
return value;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取和targetKey匹配的一个子节点
*
* @param targetKey
* @param parentElement
* @return
* @author banxian
* @date: 2021/1/21 19:53
*/
public Element getTargetElement(String targetKey, Element parentElement) {
Iterator iterator = parentElement.elementIterator();
Element childElement = null;
while (iterator.hasNext()) {
Element element = (Element) iterator.next();
Attribute attribute = (Attribute) element.attributes().get(0);
String key = attribute.getValue();
if (key.equals(targetKey) || key == targetKey) {
childElement = element;
break;
}
}
return childElement;
}