XML封装与验证消息
Document document = DocumentHelper.createDocument(); document.setXMLEncoding(ChARSET_UTF_8); Element root = document.addElement("message"); Element head = root.addElement("head"); head.addElement("field").addAttribute("name"," ").setText(""); Element body = root.addElement("body"); body.addElement("field").addAttribute("name","").setText(""); return document.asXML();
一般用于封装消息 发送XML通知等。
用于判断XML中的元素:
Document document = DocumentHelper.parseText(input); Element root = document.getRootElement(); Element headElement = root.element("head"); Preconditions.checkArgument(headElement != null,"XML中无head元素"); setData(dataMap,bodyElement); Element bodyElement = root.element("body"); Preconditions.checkArgument(bodyElement != null,"XML中无body元素; setData(dataMap,BodyElement); public void setData(Map<String,Object> dataMap,Element parentElement){ List<Element> fieldElements = parentElement.elements("field"); Preconditions.checkArgument((fieldElements != null && fieldElements.isEmpty()),"XML缺少field元素"); for(Element fieldElement : fieldElements){ String name = fieldElement.attributeValue("name"); String value = StringUtils.trimToNull(fieldElement.getTextTrim()): dataMap.put(name,value); } }