引入Dom4j依赖
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
Dom4j解析
public static void main(String[] args) {
String xml = "<Response retCode=\"000\" scoreID=\"1920011\" score=\"848\" fraud=\"5\" />";
InputStream is = null;
try {
SAXReader reader = new SAXReader();
is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
Document doc = reader.read(is);
Element root = doc.getRootElement();
String retCode = root.attributeValue("retCode");
String scoreID = root.attributeValue("scoreID");
String score = root.attributeValue("score");
String fraud = root.attributeValue("fraud");
System.out.println("retCode: " + retCode + " scoreID: " + scoreID + " score: " + score + " fraud: " + fraud);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
处理结果
retCode: 000 scoreID: 1920011 score: 848 fraud: 5
本文介绍如何使用Dom4j库解析XML字符串,并提取关键属性值。通过具体示例展示了Dom4j的基本用法,包括创建SAXReader对象、读取XML内容、获取根元素及属性值。
1417

被折叠的 条评论
为什么被折叠?



