xml解析

一,XML文件解析

  1)在接口调用中返回值有时返回的是XML格式的字符串

二,解析

  1)把返回的字符串转换成Document

  2)获取内容


import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

String xml="XML字符串";
        // 创建xml解析对象
           SAXReader reader = new SAXReader();
        // 定义一个文档
           Document document = null;
           //将字符串转换为
           try {
            document = reader.read(new ByteArrayInputStream(xml.getBytes("utf-8")));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
           
          //读取根节点
            Element productsEle = document.getRootElement();
            
            //读取products的子节点
            Iterator<Element> it1 = productsEle.elementIterator();
            
            //遍历子节点
            while(it1.hasNext()){//判断是否有下一个子元素
                //子节点
                Element productEle = it1.next();
                System.out.println("子节点名字-->"+productEle.getName()+"  内容:"+productEle.getText());
                //获取属性
                List<Attribute> attrs =  productEle.attributes();
                //遍历attrs读取所有的属性
                for (Attribute att : attrs) {
                    System.out.println("属性"+att.getName()+":===="+att.getText());
                }
                Iterator<Element> it2 = productEle.elementIterator();
                //遍历product标签的子元素
                while(it2.hasNext()){
                    //获取每个子元素
                    Element eles = it2.next();
                    System.out.println(eles.getName()+"==="+eles.getText());
                }
                
                System.out.println();
            }
原文地址:https://www.cnblogs.com/hi-feng/p/8033925.html