解析xml,獲取xml中的值


import com.github.pagehelper.util.StringUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

public class Analyxml {

public Map<String, Object> map = new HashMap<String, Object>();
public Set hais = new HashSet();

public Map<String, Object> parse(String soap) throws DocumentException {
Document doc = DocumentHelper.parseText(soap);// 報文轉成doc對象
Element root = doc.getRootElement();// 獲取根元素,准備遞歸解析這個XML樹
getCode(root);
return map;
}

public void getCode(Element root) {
if (root.elements() != null) {
List<Element> list = root.elements();// 如果當前跟節點有子節點,找到子節點
for (Element e : list) {// 遍歷每個節點
if (e.elements().size() > 0) {
getCode(e);// 當前節點不為空的話,遞歸遍歷子節點;
}//a 標簽可以為null,b標簽 不可以為null
       //要把&&的條件放||前面,放||后面會出現不生效的情況,必須不能為null的存入map集合中
if (e.elements().size() == 0 && StringUtil.isEmpty(e.getTextTrim()) && e.getName()=="Hhhh" || e.getName()=="table" ) {
map.put(e.getName(), e.getTextTrim());
} // 如果為葉子節點,那么直接把名字和值放入map
}
}
}
}



public class test2 {

public static void main(String[] args) throws DocumentException {
// TODO Auto-generated method stub

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Service><Header><table>bbxrb</table><ServiceCode></ServiceCode><Hhhh></Hhhh></Header><Header><table>ttbdb</table><ServiceCode>2</ServiceCode><Hhhh></Hhhh></Header><Header><ServiceCode>3</ServiceCode><Hhhh>3</Hhhh></Header></Service>";

Analyxml aly = new Analyxml();
Map parse = aly.parse(xml);

System.out.println(parse);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM