目的:解析xml文件,并存入mysql,并且要解析的字段能一一对应.这里解析的是微博的文件,想要利用里面的article和person_id字段.

思路:

为了能得到person_id和article能一一对应.因此对两个字段分别解析,并且定义一个私有变量ct,在重载的函数startElement中自动加1.这个ct作为插入mysql中的article和person_id的主键即(ct,article)和(ct,person_id),在分别插入两张不同的表a和b之后,两个表做连接操作,实现article和person_id的一一对应(曲线救国啊!!!)

import javax.xml.parsers.SAXParser;   
import javax.xml.parsers.SAXParserFactory;   
import org.xml.sax.Attributes;   
import org.xml.sax.InputSource;   
import org.xml.sax.SAXException;   
import org.xml.sax.helpers.DefaultHandler;   
 
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

public class sax_parse_xml extends DefaultHandler {   
 
java.util.Stack tags = new java.util.Stack();   
  private long ct=0;
public static boolean isLegalXMLCharacter(int ch) {  
    if (ch <= 0xD7FF) {  
        if(ch<=0x0){return false;}
        if (ch >= 0x20) {  
            return true;  
        } else {  
            return ch == '\n' || ch == '\r' || ch == '\t';  
        }  
    }
    else{  
        return (ch >= 0xE000 && ch <= 0xFFFD) || (ch >= 0x10000 && ch <= 0x10FFFF);  
    }  
    
    
    
}  

public sax_parse_xml() {   
  super();   
}   
 
public static void main(String args[]) {   
  long lasting = System.currentTimeMillis();   
  try {   
    SAXParserFactory sf = SAXParserFactory.newInstance();   
    SAXParser sp = sf.newSAXParser();   
    sax_parse_xml reader = new sax_parse_xml();   
    sp.parse(new InputSource("/home/hadoop/weibo_content_corpus/nlpir_weibo_content"), reader);   
   } catch (Exception e) {   
    e.printStackTrace();   
   }   
 
  System.out.println((int)'运');
   System.out.println("运行时间:" + (System.currentTimeMillis() - lasting)   
     + "毫秒");   
}   
 
public void characters(char ch[], int start, int length)   
   throws SAXException {   
   String tag = (String) tags.peek();   
   String ch1 = "";
   String ch2="";
   //System.out.print(ch.length);
   //long ct=0;
   
 //下面的程序向文件写入解析的xml的结果
   File file = new File("/home/hadoop/weibo_content_corpus", "addfile.txt");  
   if(!file.exists())
   {
       try {  
       file.createNewFile(); // 创建文件  
   } catch (IOException e) {  
       // TODO Auto-generated catch block  
       e.printStackTrace();  
   }  
   }
   
   File file1 = new File("/home/hadoop/weibo_content_corpus", "add_id.txt");  
   if(!file1.exists())
   {
       try {  
       file1.createNewFile(); // 创建文件  
   } catch (IOException e) {  
       // TODO Auto-generated catch block  
       e.printStackTrace();  
   }  
   }
   // 向文件写入内容(输出流)  
   String str = "java外挖出1\n";  
   byte bt[] = new byte[1024];  
   bt = str.getBytes();
  /* try {  
       // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件  
       FileWriter writer = new FileWriter("/home/hadoop/weibo_content_corpus/addfile.txt", true);  
       writer.write(str);  
       writer.close();  
   } catch (IOException e) {  
       e.printStackTrace();  
   }*/  
   //上面的程序向文件写入解析的xml的结果
   
   if (tag.equals("article")) {   
       System.out.println("article:");
       String tmpStr=new String(ch, start, length);
       if(tmpStr.trim().length()>0)
       {
       //System.out.println(new String(ch, start, length));
       ch1="insert into tb_xml_article_hd1 values ("+ct+","+"\""+tmpStr+"\""+");";//生成导入mysql的脚本
       bt = ch1.getBytes();
       try {  
           // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件  
           FileWriter writer = new FileWriter("/home/hadoop/weibo_content_corpus/addfile.txt", true);  
           writer.write(ch1+"\n"+"commit;"+"\n");  
           writer.close();  
       } catch (IOException e) {  
           e.printStackTrace();  
       }  
       System.out.println(ch1);
      // ct++;
       //StringBuffer sb = new StringBuffer();
       //sb.delete(0, sb.length());
       /*
       for (int i=start;i<length;i++)
       {
           
           if(Character.isDefined(ch[i]))//(isLegalXMLCharacter(ch[i]))
           {
              //System.out.println(ch[i]);
           }
       }*/
      // System.out.println(start);
       //System.out.println(length);
       //sb.append(ch, start, length);
          //System.out.println(ch1);
       }
   }
   if (tag.equals("person_id")) {   
       //ch1=ct+":"+new String(ch, start, length);
       String tmpStr=new String(ch, start, length);
       if(tmpStr.trim().length()>0)
       {
       /*ch1="insert into tb_xml_person_hd values ("+(ct-4)+","+"\""+tmpStr+"\""+");";
       bt = ch1.getBytes();
       try {  
           // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件  
           FileWriter writer = new FileWriter("/home/hadoop/weibo_content_corpus/add_id.txt", true);  
           writer.write(ch1+"\n"+"commit;"+"\n");  
           writer.close();  
       } catch (IOException e) {  
           e.printStackTrace();  
       }  
       System.out.println(ch1);
       */
       }
    //System.out.println("personid:");
    //System.out.println( new String(ch, start, length));
  //  ch1=ch1+new String(ch, start, length);
       //ch1=new String(ch, start, length);
      // ch2=new String(ch, start, length);
      // System.out.println(ch1);
   }   
 
 
  if (tag.equals("time")) {   
     // System.out.println("time:");
     // System.out.println(new String(ch, start, length));
     // ch1=ch1+new String(ch, start, length);
      //ch1.concat(new String(ch, start, length));
      //System.out.println(ch1);
   }   
//  System.out.println(ch1);
  //ch1="";
 
 
}   
 
public void startElement(String uri, String localName, String qName,   
    Attributes attrs) {   
   tags.push(qName);  
   ct=ct+1;
   //System.out.println(ct);
}   
}

java使用sax解析xml的更多相关文章

  1. Java用SAX解析XML

    要解析的XML文件:myClass.xml <?xml version="1.0" encoding="utf-8"?> <class> ...

  2. JAVA使用SAX解析XML文件

    在我的另一篇文章(http://www.cnblogs.com/anivia/p/5849712.html)中,通过一个例子介绍了使用DOM来解析XML文件,那么本篇文章通过相同的XML文件介绍如何使 ...

  3. Java中Sax解析XML

    SAX基于事件的解析,解析器在一次读取XML文件中根据读取的数据产生相应的事件,由应用程序实现相应的事件处理逻辑,即它是一种“推”的解析方式:这种解析方法速度快.占用内存少,但是它需要应用程序自己处理 ...

  4. 简单的java使用SAX解析xml

    1.新建一个SAXTest类,继承import org.xml.sax.helpers.DefaultHandler类 package com.qiao.SrpingSource; import or ...

  5. java 使用SAX解析xml 文件

    http://www.cnblogs.com/allenzheng/archive/2012/12/01/2797196.html 为了学习方便,忘博主勿究

  6. SAX解析XML笔记

    关于基本操作,请参考:Java用SAX解析XML,这里不重复造轮子了,以下是个人笔记:

  7. 用SAX解析xml文件,java

    (此文为(https://www.imooc.com/video/4482)之随笔) 1.用SAX解析xml文件大致分为三步 写了一个XML文件作为例子 (1)main方法代码如下: import j ...

  8. Android之SAX解析XML

    一.SAX解析方法介绍 SAX(Simple API for XML)是一个解析速度快并且占用内存少的XML解析器,非常适合用于Android等移动设备. SAX解析器是一种基于事件的解析器,事件驱动 ...

  9. DOM&SAX解析XML

    在上一篇随笔中分析了xml以及它的两种验证方式.我们有了xml,但是里面的内容要怎么才能得到呢?如果得不到的话,那么还是没用的,解析xml的方式主要有DOM跟SAX,其中DOM是W3C官方的解析方式, ...

随机推荐

  1. 原生js实现网页触屏滑动

    前言: 我有一个html格式的2048游戏,可以用键盘上下左右操作,但是放到手机上就抓瞎了.于是想修改一下代码,将键盘事件改成手机触屏事件. html5 的touch事件 html5支持touch事件 ...

  2. C#实现对远程服务器的内存和CPU监控

    C#实现对远程服务器的内存和CPU监控小记 1.  主要使用到的组件有System.Management.dll 2.  主要类为 :ManagementScope 连接远程服务器示例代码: priv ...

  3. Eclipse设置选中高亮显示

    高亮显示选中的变量对于程序员编程很有帮助,正常情况下Eclipse选中变量时都会高亮显示,可能软件冲突导致高亮显示失效,通过如下方法可以进行恢复. 单击IDE顶部Window菜单下的Prefences ...

  4. glob模块

    Python模块(glob) 主要是用来在匹配文件,相当于在shell中用通配符匹配.  参考:  http://python.usyiyi.cn/python_278/library/glob.ht ...

  5. Python之路----------random模块

    随机数模块: import random #随机小数 print(random.random()) #随机整数 print(random.randint(1,5))#他会打印5 #随机整数 print ...

  6. option(recompile)

    Ref: http://www.cnblogs.com/CareySon/archive/2013/05/04/PlanCacheInSQLServerPart2.html https://msdn. ...

  7. SpringMVC整合Hibernate实现增删改查之按条件查询

    首先我贴出我项目的结构,只完成了条件查询的相关代码,增删改没有写. 1.新建一个动态Web工程,导入相应jar包,编写web.xml配置文件 <context-param> <par ...

  8. 使用Vue构建中(大)型应用

    init 首先要起一个项目,推荐用vue-cli安装 $ npm install -g vue-cli $ vue init webpack demo $ cd demo $ npm install ...

  9. 开始学习bizTalk server了

    开始学习bizTalk Server 2013 R2了,有兴趣的朋友可以关注我,一同学习

  10. C#先序遍历2叉树(非递归)

    找了下先序遍历二叉树C# 实现貌似没有 顺手些了一个 大致思路是: 传入根节点,然后依次循环其子节点推入到栈中, 当推入的节点没有子节点的时候(叶子)或者所有子节点均已经遍历过后(上一次遍历的节点是该 ...