如何从Java中的URL XML响应,并将其存储在MongoDB中
问题描述:
我想请求一个URL将返回类似以下内容的XML响应:如何从Java中的URL XML响应,并将其存储在MongoDB中
<SERVERPERFORMANCEMETRICS>
<SERVERNAME>abc</SERVERNAME>
<SERVERSTARTUPTIME>11/25/2016 11:00 AM</SERVERSTARTUPTIME>
<TOTALMASTERREQUESTS>4</TOTALMASTERREQUESTS>
<TOTALRENDERERREQUESTS>13</TOTALRENDERERREQUESTS>
<FAILEDREQUESTS>10</FAILEDREQUESTS>
</SERVERPERFORMANCEMETRICS>
,现在我想分析和存储该XML的数据在MONGODB。
URL url;
HttpURLConnection urlConnection = null;
MongoClientURI mongoClientURI = new MongoClientURI(dbURL);
MongoClient mongoClient = new MongoClient(mongoClientURI);
/* To connect database, you need to specify the database name, if the database
doesn't exist then MongoDB creates it automatically. */
MongoDatabase mongoDatabase = mongoClient.getDatabase("myDb");
System.out.println("Connected to database successfully");
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("myCollection");
System.out.println("Collection created successfully");
url = new URL(targetURL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
答
我用自己JSON-java的罐子
if (inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = bufferedReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
JSONObject jsonObject = XML.toJSONObject(responseStrBuilder.toString());
System.out.println(jsonObject);
org.bson.Document jsonDocument = org.bson.Document.parse(jsonObject.toString());
mongoCollection.insertOne(jsonDocument);
System.out.println("Collection inserted successfully");
}
答
使用W3C的DocumentBuilder
:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(inputStream);
请,张贴XML作为代码,而不是作为图片找到了解决办法。 –
' ABC 2016年11月25日上午11时 SERVERSTARTUPTIME> 4 TOTALMASTERREQUESTS> 13 TOTALRENDERERREQUESTS> 10 SERVERPERFORMANCEMETRICS>' –