日期:2014-05-16 浏览次数:20443 次
?
package com.cash.xml; import java.io.IOException; import java.io.InputStream; import java.net.UnknownHostException; import org.apache.commons.io.IOUtils; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; import net.sf.json.JSON; import net.sf.json.xml.XMLSerializer; public class ConvertXMLtoJSON { public static void app() throws IOException { try { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("myDB"); DBCollection collection = db.getCollection("MyKeySpace"); InputStream is = ConvertXMLtoJSON.class .getResourceAsStream("sample.xml"); String xml = IOUtils.toString(is); System.out.println(xml); XMLSerializer xmlSerializer = new XMLSerializer(); JSON json = xmlSerializer.read(xml); // convert JSON to DBObject directly DBObject object = (DBObject) com.mongodb.util.JSON.parse(json .toString()); collection.insert(object); DBCursor cursorDoc = collection.find(); while (cursorDoc.hasNext()) { System.out.println(cursorDoc.next()); } System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { app(); } }