项目中做消息签名验证需要将xml各个节点值相加,采用dom4j和jdom分别实现。
dom4j:
- import org.dom4j.Document;
- import org.dom4j.DocumentException;
- import org.dom4j.DocumentHelper;
- import org.dom4j.Element;
- String xml="<?xml version="1.0 " encoding="UTF-8"><Order><Cid>456</Cid><Pwd& gt;密码</Pwd><Pid>商品单号</Pid><Price>商品价格< /Price></Order>";
- try {
- Document doc = DocumentHelper.parseText(xml);
- SAXReader reader = new SAXReader();
- Element el=doc.getRootElement();
- for(Iterator it=el.elementIterator();it.hasNext();){
- Element element = (Element) it.next();
- System.out.println(element.getText());
- }
- } catch (DocumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
jdom实现如下:
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.JDOMException;
- import org.jdom.Namespace;
- import org.jdom.input.SAXBuilder;
- public List xmlElements(String xmlDoc) {
- //创建一个新的字符串
- StringReader read = new StringReader(xmlDoc);
- //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
- InputSource source = new InputSource(read);
- //创建一个新的SAXBuilder
- SAXBuilder sb = new SAXBuilder();
- try {
- //通过输入源构造一个Document
- Document doc = sb.build(source);
- //取的根元素
- Element root = doc.getRootElement();
- //得到根元素所有子元素的集合
- List jiedian = root.getChildren();
- //获得XML中的命名空间(XML中未定义可不写)
- Namespace ns = root.getNamespace();
- Element et = null;
- for(int i=0;i<jiedian.size();i++){
- et = (Element) jiedian.get(i);//循环依次得到子元素
- System.out.println(et.getValue());
- }
- }
- } catch (JDOMException e) {
- // TODO 自动生成 catch 块
- e.printStackTrace();
- } catch (IOException e) {
- // TODO 自动生成 catch 块
- e.printStackTrace();
- }
- return null;
- }
- public static void main(String[] args) throws Exception{
- String xml0="<?xml version="1.0 " encoding="UTF-8"?><Order><Cid>456</Cid>< Pwd>密码</Pwd><Pid>商品单号< /Pid><Prices><Price>商品价格01</Price><Price>商品价格 02</Price></Prices></Order>";
- doc.xmlElements(xml0);
- }
以上只能实现树结构2层的XML,以下递归出多层XML节点值:
- public static String getXmlElmentValue(String xml){
- StringBuffer str=new StringBuffer();
- try {
- org.dom4j.Document doc= DocumentHelper.parseText(xml);
- org.dom4j.Element el=doc.getRootElement();
- return recGetXmlElementValue(el,str).toString();
- } catch (DocumentException e) {
- e.printStackTrace();
- return null;
- }
- }
- private static StringBuffer recGetXmlElementValue(org.dom4j.Element ele,StringBuffer valueBuff){
- List eleList = ele.elements();
- if(eleList.size()==0){
- valueBuff.append(ele.getText().replaceAll("[ - ]", ""));
- return valueBuff;
- }else{
- for(Iterator<org.dom4j.Element> iter = eleList.iterator();iter.hasNext();){
- org.dom4j.Element innerEle = iter.next();
- recGetXmlElementValue(innerEle,valueBuff);
- }
- return valueBuff;
- }
- }