2016-11-25 58 views
1

我想請求一個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); 
+1

請,張貼XML作爲代碼,而不是作爲圖片找到了解決辦法。 –

+0

' ABC 2016年11月25日上午11時 4 13 10 ' –

回答

0

我用自己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"); 
     } 
0

使用W3C的DocumentBuilder

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
Document doc = builder.parse(inputStream); 
相關問題