解析xml文件并且输出(SAX解析器)

Posted 5aixin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解析xml文件并且输出(SAX解析器)相关的知识,希望对你有一定的参考价值。

本文解析三个xml文件,难度依次增加

文件1:p1.xml

<?xml version="1.0" encoding="UTF-8" ?>
<persons>
    <person>
      <name>张三</name>
      <age>22</age>
   </person>
</persons>

文件2:p2.xml

<?xml version="1.0" encoding="UTF-8" ?>
<persons>
    <person>
      <name>张三</name>
      <age>33</age>
   </person>
   <person>
      <name>李四</name>
      <age>44</age>
   </person>
</persons>

 

文件3:p3.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>cs.cwnu.servlet.LoginServlet
        </servlet-class>
    </servlet>
    <servlet>
        <servlet-name>reg</servlet-name>
        <servlet-class>cs.cwnu.servlet.RegisterServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
        <url-pattern>/g</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>reg</servlet-name>
        <url-pattern>/reg</url-pattern>
    </servlet-mapping>
</web-app>

 

首先解析文件1

public class XmlTest 

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException 
        //SAX解析
        //1、获取解析工厂
        SAXParserFactory factory=SAXParserFactory.newInstance();
        //2、从解析工厂获取解析器
        SAXParser parse =factory.newSAXParser();
        //3、编写处理器
        //4、加载文档 Document 注册处理器
        PHandler handler=new PHandler();
        //5、解析
        parse.parse(Thread.currentThread().getContextClassLoader()
        .getResourceAsStream("cs/cwnu/test/p1.xml")
        ,handler);

    


class PHandler extends DefaultHandler
    @Override
    public void startDocument() throws SAXException 
        System.out.println("----解析文档开始----");
    
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
        System.out.println(qName+"元素解析开始");
    
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException 
        String contents = new String(ch,start,length).trim();
        if(contents.length()>0) 
            System.out.println("内容为"+contents);            
        else 
            System.out.println("内容为空");        
        
    
    
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException 
        System.out.println(qName+"元素解析结束");
    
    @Override
    public void endDocument() throws SAXException 
        System.out.println("----解析文档结束----");
    

结果展示
技术图片
----解析文档开始----
persons元素解析开始
内容为空
person元素解析开始
内容为空
name元素解析开始
内容为张三
name元素解析结束
内容为空
age元素解析开始
内容为22
age元素解析结束
内容为空
person元素解析结束
内容为空
内容为空
persons元素解析结束
----解析文档结束----
View Code

其次解析文件2

public class XmlTest02 

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException 
        //SAX解析
        //1、获取解析工厂
        SAXParserFactory factory=SAXParserFactory.newInstance();
        //2、从解析工厂获取解析器
        SAXParser parse =factory.newSAXParser();
        //3、编写处理器
        //4、加载文档 Document 注册处理器
        PersonHandler handler=new PersonHandler();
        //5、解析
        parse.parse(Thread.currentThread().getContextClassLoader()
        .getResourceAsStream("cs/cwnu/test/p2.xml")
        ,handler);
        
        //获取数据
        List<Person> persons = handler.getPersons();
        for(Person p:persons) 
            System.out.println(p.getName()+"-->"+p.getAge());
        
    


class PersonHandler extends DefaultHandler
    private List<Person> persons ;
    private Person person ;
    private String tag; //存储操作标签
    @Override
    public void startDocument() throws SAXException 
        persons = new ArrayList<Person>();
    
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
        if(null!=qName) 
            tag = qName; //存储标签名
            if(tag.equals("person")) 
                person = new Person();
            
        
    
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException 
        String contents = new String(ch,start,length).trim();
        if(null!=tag)  //处理了空
            if(tag.equals("name")) 
                person.setName(contents);
            else if(tag.equals("age")) 
                if(contents.length()>0) 
                    person.setAge(Integer.valueOf(contents));
                            
            
        
    
    
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException 
        if(null!=qName)  
            if(qName.equals("person")) 
                persons.add(person);
            
        
        tag = null; //tag丢弃了
    
    @Override
    public void endDocument() throws SAXException 
    

    public List<Person> getPersons() 
        return persons;
    

结果为:

张三-->33
李四-->44

最后解析文件3:p3.xml

用户访问的网址不同,会访问不同的Servlet

比如:访问“/login或/g”,用户会跳转到LoginServlet

访问“/reg”,用户会跳转到RegisterServlet

具体代码如下:

创建Entity类用来存放<Servlet>元素的内容

技术图片
package cs.cwnu.servlet;

//<servlet>
//<servlet-name>login</servlet-name>
//<servlet-class>com.sxt.server.basic.servlet.LoginServlet
//</servlet-class>
//</servlet>

public class Entity 
    private String name;
    private String clz;
    public Entity()
        
    
    /**
     * @param name
     * @param clz
     */
    public Entity(String name, String clz) 
        super();
        this.name = name;
        this.clz = clz;
    
    public String getName() 
        return name;
    
    public void setName(String name) 
        this.name = name;
    
    public String getClz() 
        return clz;
    
    public void setClz(String clz) 
        this.clz = clz;
    
    
View Code

创建Mapping类来存放<ServletMapping>元素的内容

技术图片
package cs.cwnu.servlet;

import java.util.HashSet;
import java.util.Set;
//<servlet-mapping>
//<servlet-name>login</servlet-name>
//<url-pattern>/login</url-pattern>
//<url-pattern>/g</url-pattern>
//</servlet-mapping>
public class Mapping 
    private String name;
    private Set<String> patterns;
    /**
     * @param name
     * @param patterns
     */
    public Mapping() 
        patterns = new HashSet<String>();
    
    public Mapping(String name, Set<String> patterns) 
        super();
        this.name = name;
        this.patterns = patterns;
    
    public String getName() 
        return name;
    
    public void setName(String name) 
        this.name = name;
    
    public Set<String> getPatterns() 
        return patterns;
    
    public void setPatterns(Set<String> patterns) 
        this.patterns = patterns;
    
    public void addPattern(String pattern)
        this.patterns.add(pattern);
    
View Code

创建Servlet接口

技术图片
package cs.cwnu.servlet;

public interface Servlet 
    void service();
View Code

创建LoginServlet实现Servlet类

技术图片
package cs.cwnu.servlet;

public class LoginServlet implements Servlet 

    @Override
    public void service() 
        System.out.println("LoginServlet");
    

View Code

创建RegisterServlet实现Servlet类

技术图片
package cs.cwnu.servlet;

public class RegisterServlet implements Servlet 

    @Override
    public void service() 
        System.out.println("RegisterServlet");
    

View Code

创建WebContext类,功能是用户输入url通过匹配<servlet-mapping>中的<url-pattern>的值,找到同级<servlet-name>的值,再找到与<servlet>中<servlet-name>值相同且同级的<servlet-class>的值,即找到Servlet类

技术图片
package cs.cwnu.servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebContext 
    private List<Entity> entitys=null;
    private List<Mapping> mappings=null;
    //key:servlet-name,value:servlet-class
    private Map<String,String> entityMap = new HashMap<String,String>();
    //key:url-pattern,value:servlet-name
    private Map<String,String> mappingMap = new HashMap<String,String>();
    
    /**
     * @param entitys
     * @param mappings
     */
    public WebContext(List<Entity> entitys, List<Mapping> mappings) 
        super();
        this.entitys = entitys;
        this.mappings = mappings;
        for (Entity entity : entitys) 
            entityMap.put(entity.getName(), entity.getClz());
        
        for (Mapping mapping : mappings) 
            for(String pattern:mapping.getPatterns())
                mappingMap.put(pattern, mapping.getName());
            
        
    
    public String getClz(String pattern)
        String name = mappingMap.get(pattern);
        String clas = entityMap.get(name);
        return clas;
    
View Code

测试代码:

技术图片
package cs.cwnu.servlet;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlTest01 

    public static void main(String[] args) throws Exception
        // SAX解析
        // 1、获取解析工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // 2、从解析工厂获取解析器
        SAXParser parse = factory.newSAXParser();
        // 3、编写处理器
        // 4、加载文档 Document 注册处理器
        WebHandler handler = new WebHandler();
        // 5、解析
        parse.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("cs/cwnu/servlet/web.xml"), handler);
        List<Entity> entitys = handler.getEntitys();
        List<Mapping> mappings = handler.getMappings();
        WebContext wb = new WebContext(entitys, mappings);
        
        //假设登录
        //String name = wb.getClz("/login");输出LoginServlet
        String name = wb.getClz("/g");
        //String name = wb.getClz("/reg");输出RegisterServlet
        Class clazz = Class.forName(name);
        Servlet servlet = (Servlet)clazz.getConstructor().newInstance();
        servlet.service();
    



class WebHandler extends DefaultHandler 
    private List<Entity> entitys;
    private List<Mapping> mappings;
    private Entity entity;
    private Mapping mapping;
    private String tag;
    private boolean isMapping = false;

    @Override
    public void startDocument() throws SAXException 
        entitys = new ArrayList<Entity>();
        mappings = new ArrayList<Mapping>();
    

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
        if (null != qName) 
            tag = qName;
            if (tag.equals("servlet")) 
                entity = new Entity();
                isMapping = false;
             else if (tag.equals("servlet-mapping")) 
                mapping = new Mapping();
                isMapping = true;
            
        
    

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException 
        String contents = new String(ch, start, length).trim();
        if (null != tag) 
            if (isMapping) 
                if (tag.equals("servlet-name")) 
                    mapping.setName(contents);
                 else if (tag.equals("url-pattern")) 
                    mapping.addPattern(contents);
                
             else 
                if (tag.equals("servlet-name")) 
                    entity.setName(contents);
                 else if (tag.equals("servlet-class")) 
                    entity.setClz(contents);
                
            

        

    

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException 
        if (null != qName) 
            if (qName.equals("servlet")) 
                entitys.add(entity);
             else if (qName.equals("servlet-mapping")) 
                mappings.add(mapping);
            

        
        tag = null;

    

    @Override
    public void endDocument() throws SAXException 
    

    public List<Entity> getEntitys() 
        return entitys;
    

    public List<Mapping> getMappings() 
        return mappings;
    

View Code

测试结果:LoginServlet

 

以上是关于解析xml文件并且输出(SAX解析器)的主要内容,如果未能解决你的问题,请参考以下文章

xml 使用 sax 解析器从子标签解析数据

使用 SAX 解析器解析 Xml

使用 SAX 解析器,如何解析具有相同名称标签但元素不同的 xml 文件?

解析XML文件之使用SAM解析器

dom4j解析器sax解析xml文件

在 zip 中的 xml 文件上使用 SAX 解析器