dom4j将xml转换为json
//用于判断是否有子节点,若有就将子节点也进行拼接,若无则返回"" public String checkChildEle(Element element) throws DocumentException{
String json="";
List<Element> list = new ArrayList<Element>();
list=element.elements();
if (list.size()>0) {
for (Element ele : list) {
json+=ele.getName()+":"+ele.getText()+","+"\r\n"+checkChildEle(ele); } }
return json; }
//这个方法是将xml字符串转成Json
public String xmlChangeJson(String XML) throws DocumentException{
Document document=DocumentHelper.parseText(XML);
Element root=document.getRootElement();
Iterator it=root.elementIterator();
String json="{";
while (it.hasNext()) {
Element element =(Element)it.next();
String j=checkChildEle(element);
if (j=="") { json+=element.getName()+":"+element.getText()+","+"\r\n";
}else {
json+=j;
}
}
json+="}";
return json; }
//这个方法是将xml文件转成Json
public String xmlChangeJson(File XML) throws DocumentException{
SAXReader reader=new SAXReader();
Document document=reader.read(XML);
Element root=document.getRootElement();
Iterator it=root.elementIterator();
String json="{";
while (it.hasNext()) {
Element element =(Element)it.next();
String j=checkChildEle(element);
if (j=="") {
json+=element.getName()+":"+element.getText()+","+"\r\n";
}else {
json+=j;
}
}
json+="}";
return json; }