zoukankan      html  css  js  c++  java
  • XML解析与xml和Map集合的互转

    1.XML的解析、首先解析XML文件我们需要先获取到文件的存放路径,获取方法有三种分别获取xml文件不同的存放路径。

    代码:

     1 public class PropertiesDemo {
     2 
     3     public static void main(String[] args) throws IOException {
     4         //获取到同包下的资源文件,将其转换成流对象
     5         //InputStream in=PropertiesDemo.class.getResourceAsStream("db.properties");
     6         //获取资源文件存放在根目录下
     7         InputStream in=PropertiesDemo.class.getResourceAsStream("/db.properties");
     8         
     9         //需要专门的工具类来将流中的数据解析出来
    10         Properties p=new Properties(); 
    11         p.load(in)
    12         System.out.println(p.getProperty("uname"));
    13         System.out.println(p.getProperty("url"));
    14     }
    15
     

    这里是当xml文件存放在WEB-INF目录下时的获取方法,代码跟上面两种差不多只是需要新建一个Servlet。

    package com.zking.parse;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ParseServlet extends HttpServlet {
    
     /**
      * 
      */
     private static final long serialVersionUID = 7819852743461108632L;
    
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      
      doPost(req, resp);
     }
     
     @Override
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      
      ServletContext context=req.getServletContext();
      
      InputStream in=context.getResourceAsStream("/WEB-INF/db.properties");
    
      Properties p=new Properties(); 
      p.load(in);
      System.out.println(p.getProperty("uname"));
      System.out.println(p.getProperty("url"));
     }
     
     
    }

    xml解析代码:

    public class XmlDemo {
    
        
        public static void main(String[] args) throws Exception {
            InputStream in=XmlDemo.class.getResourceAsStream("students.xml");        
            SAXReader sax= new SAXReader();
            Document doc=sax.read(in);
    //        System.out.println(doc.asXML());
            //Xpath解析  能够将xml格式的串当作目录结构来进行查找
            List<Element> stuEles= doc.selectNodes("/students/student");
            for (Element stuEle : stuEles) {
                if("s002".equals(stuEle.attributeValue("sid"))) {
                    System.out.println(stuEle.asXML());
                    Element nameEle=(Element) stuEle.selectSingleNode("name");
                    System.out.println(nameEle.asXML());
                    System.out.println(nameEle.getText());
                }
            }

    2.将xml文件转换为map集合。

    代码:

    将XML文档转换为Map集合,方式也比较多,下面这种方式是DOM4J的方式:
    
    Map<String, String> map=new HashMap<String,String>();
    try {
    InputStream is = new FileInputStream(new File("config.xml"));
    
    SAXReader sax=new SAXReader(); //创建解析器
    
    Document doc=sax.read(is); //创建对应的Document对象
    
    Element root=doc.getRootElement(); //获取XML文档的根节点对象
    
    List<Element> list = root.elements(); 
    //获取根节点下的所有的子节点 
    for (Element ele : list) { //遍历根节点下的所有子节点并将其放入MAP对象中
    
    map.put(ele.getName(), ele.getText());
    }
    
    is.close();
    
    } catch (Exception e) {
    e.printStackTrace();
    }

    Mpa集合转xml文件:

     /** 
         * map转xml 
         * @param map 
         * @param body xml元素 
         * @return 
         */  
        private static Element map2xml(Map<String, Object> map, Element body) {  
            Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();  
            while (entries.hasNext()) {  
                Map.Entry<String, Object> entry = entries.next();  
                String key = entry.getKey();  
                Object value = entry.getValue();  
                if(key.startsWith("@")){    //属性  
                    body.addAttribute(key.substring(1, key.length()), value.toString());  
                } else if(key.equals("#text")){ //有属性时的文本  
                    body.setText(value.toString());  
                } else {  
                    if(value instanceof java.util.List ){  
                        List list = (List)value;  
                        Object obj;  
                        for(int i=0; i<list.size(); i++){  
                            obj = list.get(i);  
                            //list里是map或String,不会存在list里直接是list的,  
                            if(obj instanceof java.util.Map){  
                                Element subElement = body.addElement(key);  
                                map2xml((Map)list.get(i), subElement);  
                            } else {  
                                body.addElement(key).setText((String)list.get(i));  
                            }  
                        }  
                    } else if(value instanceof java.util.Map ){  
                        Element subElement = body.addElement(key);  
                        map2xml((Map)value, subElement);  
                    } else {  
                        body.addElement(key).setText(value.toString());  
                    }  
                }  
                //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
            }  
            return body;  
        }  

    附加config.xml解析代码:

    //config.xml解析
    public class XmlDemo {
        public static void main(String[] args) throws Exception {
            InputStream in=XmlDemo.class.getResourceAsStream("config.xml");        
            SAXReader sax= new SAXReader();
            Document doc=sax.read(in);
           //获取所有action中的type的值
            List<Element> stuEles= doc.selectNodes("/config/action");
            for (Element stuEle : stuEles) {
                String type=stuEle.attributeValue("type");
                System.out.println(type);
                    
            }
    
     //    2、获取第二个action中的type的值
    //   List<Element> stuEles= doc.selectNodes("/config/action");
    //        for (Element stuEle : stuEles) {
    //            if("/loginAction".equals(stuEle.attributeValue("path"))) {
    //                String type=stuEle.attributeValue("type");
    //                System.out.println(type);
    //            }
    //        }
    
    
    
     //  3、获取第二个action的所有forward的path
     //  List<Element> stuEles= doc.selectNodes("/config/action");
     //       for (Element stuEle : stuEles) {
      //          if("/loginAction".equals(stuEle.attributeValue("path"))) {
      //              List<Element> ford=(List<Element>) stuEle.selectNodes("forward");
      //              for (Element element : ford) {
     //                   String path=element.attributeValue("path");
     //                   System.out.println(path);
      //              }
     //           }
     //       }
    
    
    
      // 4、获取第二个action的第二个forward的path
         //List<Element> stuEles= doc.selectNodes("/config/action");
           // for (Element stuEle : stuEles) {
             //   if("/loginAction".equals(stuEle.attributeValue("path"))) {
              //      List<Element> ford=(List<Element>) stuEle.selectNodes("forward");
                //    for (Element element : ford) {
                  //      if("success".equals(element.attributeValue("name"))) {
                 //       String path=element.attributeValue("path");
                  //      System.out.println(path);
                  //      }
                  //  }
               // }
           // }


    } }
  • 相关阅读:
    ASP.NET页面生命周期
    C#之virtual override new解析
    js之闭包、this
    C#使用定时任务框架Windows.TaskSchedule.exe安装控制台应用程序创建的Windows服务
    C# 利用 Windows服务模板 创建、安装与卸载Windows服务
    SQL代码生成器
    C#之JSON序列化与反序列化
    Vue源码学习1——Vue构造函数
    angular编写表单验证
    使用canvas编写时间轴插件
  • 原文地址:https://www.cnblogs.com/ly-0919/p/11001105.html
Copyright © 2011-2022 走看看