根据传入的XML路径获取XML中指定标签下的所有子标签,并将其封装到List
/**
*
* @param xml XML文件
* @param targetElement 需要解析的标签
* @return
* @throws DocumentException
*/
public static List<Map<String,String>> getListByXml(String xml,String targetElement) throws DocumentException {
List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
Document document = null;
document = DocumentHelper.parseText(xml);
//根据标签获取标签下的所有子标签
List<Element> condition = document.getRootElement().elements(targetElement);
for(Element element : condition){
Map<String,String> resultMap = new HashMap<String,String>();
List<Attribute> attributes = element.attributes();
if(attributes!=null&&attributes.size()>0){
for(Attribute attribute : attributes){
resultMap.put(attribute.getName(), attribute.getText().replace(" ", ""));
}
}
List<Element> elements = element.elements();
if(elements!=null&&elements.size()>0){
for(Element e : elements){
resultMap.put(e.getName(), e.getText().replace(" ", ""));
}
}
resultList.add(resultMap);
}
return resultList;
}
/**
* 根据路径获取xml
* @param xmlPath
* @return xml文件
*/
public static String getXmlByPath(String xmlPath){
InputStream in = null;
SAXReader reader = null;
Document document = null;
try {
//1.根据路径获取字节输入流
in = Resources.getResourceAsStream(xmlPath);
reader = new SAXReader();
//2.根据字节输入流获取Document对象
document = reader.read(in);
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
return document.asXML();
}
测试
@Test
public void test() throws DocumentException {
String xml = getXmlByPath("user.xml");
List<Map<String, String>> configuration = getListByXml(xml, "XMLData");
for (Map<String, String> map: configuration) {
System.out.println(map+".");
}
}
XML文件内容:
<?xml version="1.0" encoding="UTF-8" ?>
<USERINFO>
<XMLData>
<USERID>1</USERID>
<USERNAME>张三</USERNAME>
</XMLData>
<XMLData>
<USERID>2</USERID>
<USERNAME>李四</USERNAME>
</XMLData>
<XMLData>
<USERID>3</USERID>
<USERNAME>王五</USERNAME>
</XMLData>
</USERINFO>