/**
* 增加防止部实体注入逻辑
*/
public static void setReaderFeature(SAXReader reader) throws SAXException {
// 禁用DTD
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
// 禁用外部DTD
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// 禁用外部一般实体解析
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
// 禁用参数实体解析
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// 禁用限制实体解析次数
reader.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
}
[Ref] java XML解析防止外部实体注入
<?xml version="1.0" encoding="UTF-8"?>
<tests>
<test>
<id>1</id>
<name>张三</name>
<age>26</age>
<gender>男</gender>
<salary>3000</salary>
</test>
<test>
<id>2</id>
<name>李四</name>
<age>21</age>
<gender>女</gender>
<salary>2000</salary>
</test>
<test>
<id>3</id>
<name>王五</name>
<age>28</age>
<gender>女</gender>
<salary>6500</salary>
</test>
<test>
<id>4</id>
<name>赵六</name>
<age>28</age>
<gender>男</gender>
<salary>5500</salary>
</test>
<test>
<id>5</id>
<name>钱七</name>
<age>53</age>
<gender>男</gender>
<salary>12000</salary>
</test>
<cmp department="总经办">
<id>007</id>
<name>董事长</name>
<age>52</age>
<gender>男</gender>
<salary>100000</salary>
</cmp>
</tests>
public static void main(String[] args) {
try {
// 创建SAXReader
SAXReader reader = new SAXReader();
// 做安全防护
setReaderFeature(reader);
//从xml文件获取数据
Document document = reader.read(new File("D:\\projects\\utils\\xml\\test.xml"));
// 获取根节点 tests
Element root = document.getRootElement();
// 查找指定节点名称的所有子节点elements
List<Element> elements = root.elements("test");
for (Element element : elements) {
System.out.println("element.getName()==>" + element.getName());
List<Element> testElements = element.elements();
for (Element e : testElements) { //遍历emp元素下的子元素
System.out.print(e.getName() + ":"); //获取子元素名称
System.out.print(e.getText() + " "); //获取子元素的文本值
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
输出结果
element.getName()==>test
id:1 name:张三 age:26 gender:男 salary:3000
element.getName()==>test
id:2 name:李四 age:21 gender:女 salary:2000
element.getName()==>test
id:3 name:王五 age:28 gender:女 salary:6500
element.getName()==>test
id:4 name:赵六 age:28 gender:男 salary:5500
element.getName()==>test
id:5 name:钱七 age:53 gender:男 salary:12000