热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

xml格式文件(大概有50G)转换为json格式上传到mongodb数据库中

偏小数据的就不做多描述,网上有很多资料,在此有大概50G的xml格式的地理数据转换为json格式的数据,之后上传到mongodb数据库中,有什么好的建议,欢迎指正解析xml数据impor
偏小数据的就不做多描述,网上有很多资料,在此有大概50G的xml格式的地理数据转换为json格式的数据,之后上传到mongodb数据库中,有什么好的建议,欢迎指正
解析xml数据
import java.util.ArrayList;import java.util.List;import org.xml.sax.Attributes;import org.xml.sax.ContentHandler;import org.xml.sax.Locator;import org.xml.sax.SAXException;import com.mongodb.DBObject;/* * @author  * @time 2015-11-8 * 主要是是implements ContentHandler,主要实现接口ContentHandler中的startDocument()、endDocument()、startElement()、endElement() * 另外自定义方法writeToMongoDB()、storeDBMongo() *  */public class MyContentHandler implements ContentHandler {	private StringBuffer buf;	private String ctitle;	private String cns;	private String cid;	private String ctext;	private String ctimestamp;	private int idnumber=0;	List listdata=new ArrayList();	List list=new ArrayList();			@Override	public void setDocumentLocator(Locator locator) {		// TODO Auto-generated method stub	}	@Override	public void startDocument() throws SAXException {		// TODO Auto-generated method stub		buf=new StringBuffer();        System.out.println("*******解析开始*******");	}	@Override	public void endDocument() throws SAXException {		// TODO Auto-generated method stub		try {			writeToMongoDB();		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();		}		System.out.println("*******解析结束*******");			}    //把数据导入MongoDB数据库中	private void writeToMongoDB() throws Exception {		// TODO Auto-generated method stub		List dblist=new ArrayList();		for(Data d:listdata){			dblist.add(BSONT.mapToBSON(d.toJSONMap()));		}				MongoDBT.writeListToMongo("IP", 27017,"databaseName", "collectionName", dblist);	}	@Override	public void startPrefixMapping(String prefix, String uri)			throws SAXException {		// TODO Auto-generated method stub	}	@Override	public void endPrefixMapping(String prefix) throws SAXException {		// TODO Auto-generated method stub	}	@Override	public void startElement(String uri, String localName, String qName,			Attributes attributes) throws SAXException {		// TODO Auto-generated method stub					       if(qName=="page"){	    	   idnumber=1;	       }	       if(qName=="title"){	    	   ctitle=qName;	       }else if(qName=="ns"){	    	   cns=qName;	       }else if(qName=="id"&&idnumber==1){	    	   cid=qName;	    	   idnumber=0;	       }else if(qName=="timestamp"){	    	   ctimestamp=qName;	    		   	       }else if(qName=="text"){	     	   ctext=qName;	       }	       	  }	        						@Override	public void endElement(String uri, String localName, String qName)			throws SAXException {		// TODO Auto-generated method stub				if(ctitle==qName){			String sss=buf.toString();        	ctitle="";        	list.add(sss); 			buf.setLength(0); 			        }else if(cns==qName){        	cns="";        	String sss=buf.toString();       	        	list.add(sss); 			buf.setLength(0); 			        }else if(cid==qName){        	        	cid="";        	String sss=buf.toString();        	list.add(sss); 			buf.setLength(0); 			        }else if(ctimestamp==qName){        	ctimestamp="";        	String sss=buf.toString();        	list.add(sss); 			buf.setLength(0); 			        }else if(ctext==qName){        	ctext="";        	String sss=buf.toString();        	list.add(sss); 			buf.setLength(0); 			//有些sss中虽然有重定向标记,但没有“[[”和“]]”,那么就会出现String的index不在范围内的问题        	if((sss.toUpperCase().contains("#REDIRECT")||sss.contains("#重定向"))&&sss.contains("[[")&&sss.contains("]]")){        		int i=sss.indexOf("[[");        		int j=sss.indexOf("]]");        		String s=sss.substring(i+2,j);        		list.add(s);        		list.add("redirect");        	}else{       		        		list.add("");        		list.add("article");        	}        }			if(qName=="page"){				storeDBMongo(list);											}			   	}	private void storeDBMongo(List lt) {		// TODO Auto-generated method stub		for(int i=0;i=300){				writeToMongoDB();				listdata.clear();			}			list.clear();		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}	@Override	public void characters(char[] ch, int start, int length)			throws SAXException {		// TODO Auto-generated method stub        if(ctitle=="title"){        	buf.append(new String(ch,start,length));        }else if(cns=="ns"){                	buf.append(new String(ch,start,length));       	        }else if(cid=="id"){       	      	        	buf.append(new String(ch,start,length));        	list.add(new String(ch,start,length));       	        }else if(ctimestamp=="timestamp"){        	buf.append(new String(ch,start,length));        	        }else if(ctext=="text"){        	buf.append(new String(ch,start,length));        	        }        	}	@Override	public void ignorableWhitespace(char[] ch, int start, int length)			throws SAXException {		// TODO Auto-generated method stub	}	@Override	public void processingInstruction(String target, String data)			throws SAXException {		// TODO Auto-generated method stub	}	@Override	public void skippedEntity(String name) throws SAXException {		// TODO Auto-generated method stub	}	}

自定义类Data、JSONT

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


public class Data {
private String id;
private String namespace;
private String type;
private String title;
private String markup;
private String lastEsited;
private String target;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMarkup() {
return markup;
}
public void setMarkup(String markup) {
this.markup = markup;
}
public String getLastEsited() {
return lastEsited;
}
public void setLastEsited(String lastEsited) {
this.lastEsited = lastEsited;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public Map toJSONMap(){
Map jsOnmap=new HashMap();
jsonmap.put("id", this.id);
jsonmap.put("namespace", this.namespace);
jsonmap.put("type", this.type);
jsonmap.put("title", this.title);
jsonmap.put("markup", this.markup);
jsonmap.put("lastEsited", this.lastEsited);
jsonmap.put("target", this.target);
return jsonmap;
}

}


/*
* NextMap-Crawler Module
*
* Copyright (C) 2002-2014,Institute of Geographic Sciences and Natural Resources Research,
* Chinese Academy of Sciences
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/


import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
*
* @author zhuhaichuan
* @date 2015-11-8
*
*
*/

public class JSONT {
public static String mapToJSONString(Map map) {
StringWriter sw = new StringWriter();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, map);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sw.toString();
}

/**
*
* @param list
* @return
*/
public static String listToJSONString(List list) {
StringWriter sw = new StringWriter();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sw.toString();
}

/**
*
* @param list
* @return
*/
public static String beanToJSONString(Object bean) {
StringWriter sw = new StringWriter();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, bean);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sw.toString();
}

/**
*
* @param jsonstr
* @return
*/
public static Map jsonToMap(String jsonstr) {
Map map = null;
try {
ObjectMapper mapper = new ObjectMapper();
map = mapper.readValue(jsonstr, Map.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}

/**
*
* @param jsonstr
* @return
*/
public static List jsonToList(String jsonstr) {
List list = null;
try {
ObjectMapper mapper = new ObjectMapper();
list = mapper.readValue(jsonstr, List.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
还有就是类MyErrorHandler

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class MyErrorHandler implements ErrorHandler {

@Override
public void warning(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
System.out.println("*******WARNING******");
System.out.println("行号:" + exception.getLineNumber());
System.out.println("列号:" + exception.getColumnNumber());
System.out.println("exception信息:" + exception.getMessage());
System.out.println("********************");
}

@Override
public void error(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
System.out.println("******* ERROR ******");
System.out.println("行号:" + exception.getLineNumber());
System.out.println("列号:" + exception.getColumnNumber());
System.out.println("exception信息:" + exception.getMessage());
System.out.println("********************");
}

@Override
public void fatalError(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
System.out.println("******** FATAL ERROR ********");
System.out.println("行号:" + exception.getLineNumber());
System.out.println("列号:" + exception.getColumnNumber());
System.out.println("exception信息" + exception.getMessage());
System.out.println("*****************************");
}

}

自定义MongoDBT类

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

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;


public class MongoDBT {
public static void writeListToMongo(String ip,int port,String dbname,String collname,List list) throws Exception{
Mongo mOngo=new Mongo(ip,port);
DB db=mongo.getDB(dbname);
DBCollection collection=db.getCollection(collname);
List dblist=new ArrayList();
for(int i=0;i dblist.add(list.get(i));
}
collection.insert(dblist);
mongo.close();
}
}





推荐阅读
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • 本文介绍了高校天文共享平台的开发过程中的思考和规划。该平台旨在为高校学生提供天象预报、科普知识、观测活动、图片分享等功能。文章分析了项目的技术栈选择、网站前端布局、业务流程、数据库结构等方面,并总结了项目存在的问题,如前后端未分离、代码混乱等。作者表示希望通过记录和规划,能够理清思路,进一步完善该平台。 ... [详细]
  • Android JSON基础,音视频开发进阶指南目录
    Array里面的对象数据是有序的,json字符串最外层是方括号的,方括号:[]解析jsonArray代码try{json字符串最外层是 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
author-avatar
我是你的特效
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有