话不多说,看标题就够了(大家可以发现这篇和上一篇有关联,xml转json,json转bean)
package xxx;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
import java.io.ByteArrayInputStream;
import java.util.stream.Collectors;
public class XmlDemo {
public static void main(String[] args) throws DocumentException {
String str = "<Root code=\"0\" msg=\"aaaa\">" +
"<banks>" +
"<i code=\"001\" name=\"AAAA\" />" +
"<i code=\"002\" name=\"BBBB\" />" +
"<i code=\"003\" name=\"CCCC\" />" +
"</banks>" +
"</Root>";
SAXReader reader = new SAXReader(false);
InputSource source = new InputSource(new ByteArrayInputStream(str.getBytes()));
source.setEncoding("utf-8");
Document read = reader.read(source);
//封装json
JSONObject root = analysis(read.getRootElement());
System.out.println(root);
}
/**
* @param element
* @return
*/
private static JSONObject analysis(Element element){
JSONObject root = new JSONObject();
root.put("name",element.getName());
root.put("attr",JSONObject.from(element.attributes().stream().collect(Collectors.toMap(Attribute::getName, Attribute::getValue))));
root.put("cont",JSONArray.from(element.elements().stream().map(XmlDemo::analysis).collect(Collectors.toList())));
root.put("text",element.getText());
return root;
}
}