xml校驗


//功能:校驗標簽是否正確,校驗標簽值是否有空值

public class Analyxml {
/**
public static Document load(String filename) {
Document document = null;
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(new File(filename)); // 讀取XML文件,獲得document對象
} catch (Exception ex) {
ex.printStackTrace();
}
return document;
}

public boolean isOnly() {
boolean flag = true;
String path = "D:/me/testFile/xml.xml";
Document doc = load(path);
Element root = doc.getRootElement();
for (Iterator i = root.elementIterator(); i.hasNext();) {
Element el = (Element) i.next();
System.out.println(el.getName());
}
return flag;
}

public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
if(a.size() != b.size())
return false;
Collections.sort(a);
Collections.sort(b);
for(int i=0;i<a.size();i++){
if(!a.get(i).equals(b.get(i)))
return false;
}
return true;
}
*/
public Map<String, Object> map = new HashMap<String, Object>();

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);// 當前節點不為空的話,遞歸遍歷子節點;
}else(){
          //根節點,只有根節點才會有值,可以添加子節點
  
      //反,所有標簽中table可以為空,如果其他有空的且不是table的就存到map里面,這里校驗根節點是否有空值,如果校驗標簽,使用:保存所有的父節點,再校驗子節點
            if (StringUtil.isEmpty(e.getTextTrim()) && e.getName()!="table" ) {
map.put(e.getName(), e.getTextTrim());
} // 如果為葉子節點,那么直接把名字和值放入map

        }

}
}
}

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

String xml = "";

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


}
}


免責聲明!

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



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