日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

在MongoDB和Spring Batch中将XML转换为JSON和原始使用

發布時間:2023/12/3 asp.net 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在MongoDB和Spring Batch中将XML转换为JSON和原始使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

總覽

為什么將XML轉換為JSON以在MongoDB中原始使用?

由于MongoDB使用JSON文檔存儲記錄,就像表和行將記錄存儲在關系數據庫中一樣,我們自然需要將XML轉換為JSON。

某些應用程序可能需要存儲原始(未修改的)JSON,因為在如何構造數據方面存在不確定性。

有數百種基于XML的標準 。 如果應用程序要處理不遵循相同標準的XML文件,則數據的結構將存在不確定性。

為什么要使用Spring Batch?

Spring Batch提供了可重用的功能,這些功能在處理大量記錄時是必不可少的,而其他功能則可以實現高容量和高性能的批處理作業。 Spring網站已很好地記錄了Spring Batch 。

有關Spring Batch的另一個教程,請參閱我以前的文章“ 使用Spring Batch處理CSV” 。

0 –將XML轉換為JSON以在MongoDB中與Spring Batch示例應用程序一起使用

該示例應用程序轉換XML文檔,該XML文檔是用于配置音樂播放列表的“策略”。 該策略旨在類似于真實的網絡安全配置文檔。 它是一個簡短的文檔,但說明了如何搜索復雜的XML文檔。

我們將采用本教程的方法是處理各種樣式的XML文件。 我們希望能夠處理意外情況。 這就是為什么我們保持數據“原始”的原因。

1 –項目結構

它是典型的Maven結構。 我們為該示例應用程序提供了一個軟件包。 XML文件位于src / main / resources中 。

2 –項目依賴性

除了典型的Spring Boot依賴關系之外,我們還包含嵌入式MongoDB數據庫和JSON處理的依賴關系。

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.michaelcgood</groupId><artifactId>michaelcgood-spring-batch-mongodb</artifactId><version>0.0.1</version><packaging>jar</packaging><name>michaelcgood-spring-batch-mongodb</name><description>Michael C Good - XML to JSON + MongoDB + Spring Batch Example</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.7.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-batch</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>de.flapdoodle.embed</groupId><artifactId>de.flapdoodle.embed.mongo</artifactId><version>1.50.5</version></dependency><dependency><groupId>cz.jirutka.spring</groupId><artifactId>embedmongo-spring</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20170516</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

3 – XML文檔

這是為本教程創建的示例策略文檔。 它的結構基于真實的網絡安全策略文檔。

  • 請注意,文檔的父項是Policy標記。
  • 重要信息位于“組”標簽內。
  • 查看標記內的值,例如Policy中的ID或status中的日期。

在這個小文檔中有很多信息需要考慮。 例如,還有XML名稱空間(xmlns)。 在本教程的其余部分中,我們不會涉及到這一點,但是根據您的目標,可能需要為其添加邏輯。

<?xml version="1.0"?> <Policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" style="STY_1.1" id="NRD-1"><status date="2017-10-18">draft</status><title xmlns:xhtml="http://www.w3.org/1999/xhtml">Guide to the Configuration of Music Playlist</title><description xmlns:xhtml="http://www.w3.org/1999/xhtml" >This guide presents a catalog of relevantconfiguration settings for a playlist that I listen to while I work on software development.<html:br xmlns:html="http://www.w3.org/1999/xhtml"/><html:br xmlns:html="http://www.w3.org/1999/xhtml"/>Providing myself with such guidance reminds me how to efficientlyconfigure my playlist. Lorem ipsum <html:i xmlns:html="http://www.w3.org/1999/xhtml">Lorem ipsum,</html:i> and Lorem ipsum. Some example<html:i xmlns:html="http://www.w3.org/1999/xhtml">Lorem ipsum</html:i>, which are Lorem ipsum.</description><Group id="remediation_functions"><title xmlns:xhtml="http://www.w3.org/1999/xhtml" >Remediation functions used by the SCAP Security Guide Project</title><description xmlns:xhtml="http://www.w3.org/1999/xhtml" >XCCDF form of the various remediation functions as used byremediation scripts from the SCAP Security Guide Project</description><Value id="is_the_music_good" prohibitChanges="true" ><title xmlns:xhtml="http://www.w3.org/1999/xhtml" >Remediation function to fix bad playlist</title><description xmlns:xhtml="http://www.w3.org/1999/xhtml" >Function to fix bad playlist.Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsum</description><value>function fix_bad_playlist {# Load function arguments into local variablesLorem ipsumLorem ipsumLorem ipsum# Check sanity of the inputif [ $# Lorem ipsum ]thenecho "Usage: Lorem ipsum"echo "Aborting."exit 1fi}</value></Value></Group></Policy>

4 – MongoDB配置

在下面,我們指定我們使用的是嵌入式MongoDB數據庫,使它可被捆綁在便捷注釋@SpringBootApplication中的組件掃描發現,并指定mongoTemplate將是bean。

package com.michaelcgood;import java.io.IOException; import cz.jirutka.spring.embedmongo.EmbeddedMongoFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.*; import com.mongodb.MongoClient;@Configuration public class MongoConfig {private static final String MONGO_DB_URL = "localhost";private static final String MONGO_DB_NAME = "embeded_db";@Beanpublic MongoTemplate mongoTemplate() throws IOException {EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();mongo.setBindIp(MONGO_DB_URL);MongoClient mongoClient = mongo.getObject();MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME);return mongoTemplate;} }

5 –處理XML到JSON

我們的Spring Batch Job的step1()包含調用三個方法來幫助將XML轉換為JSON。 我們將分別進行審查。

@Beanpublic Step step1() {return stepBuilderFactory.get("step1").tasklet(new Tasklet() {@Overridepublic RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {// get path of file in src/main/resourcesPath xmlDocPath = Paths.get(getFilePath());// process the file to jsonString json = processXML2JSON(xmlDocPath);// insert json into mongodbinsertToMongo(json);return RepeatStatus.FINISHED;}}).build();}

5.1 – getFilePath()

此方法只是獲取作為參數傳遞給方法processXML2JSON的文件路徑。
注意:

  • ClassLoader正在幫助我們在資源文件夾中找到XML文件。
// no parameter method for creating the path to our xml fileprivate String getFilePath(){String fileName = "FakePolicy.xml";ClassLoader classLoader = getClass().getClassLoader();File file = new File(classLoader.getResource(fileName).getFile());String xmlFilePath = file.getAbsolutePath();return xmlFilePath;}

5.2 – processXML2JSON(xmlDocPath)

getFilePath返回的字符串作為參數傳遞到此方法中。 從XML文件的字符串創建一個JSONOBject。

// takes a parameter of xml path and returns json as a stringprivate String processXML2JSON(Path xmlDocPath) throws JSONException {String XML_STRING = null;try {XML_STRING = Files.lines(xmlDocPath).collect(Collectors.joining("\n"));} catch (IOException e) {e.printStackTrace();}JSONObject xmlJSONObj = XML.toJSONObject(XML_STRING);String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);System.out.println("PRINTING STRING :::::::::::::::::::::" + jsonPrettyPrintString);return jsonPrettyPrintString;}

5.3 – insertToMongo(json)

我們將已解析的JSON插入MongoDB文檔中。 然后,我們在@Autowired mongoTemplate的幫助下將此文檔插入名為“ foo”的集合中。

// inserts to our mongodbprivate void insertToMongo(String jsonString){Document doc = Document.parse(jsonString);mongoTemplate.insert(doc, "foo");}

6 –查詢MongoDB

我們的Spring Batch Job的step2()包含我們的MongoDB查詢。

  • mongoTemplate.collectionExists基于集合的存在返回一個布爾值。
  • mongoTemplate.getCollection(“ foo”)。find()返回集合中的所有文檔。
  • alldocs.toArray()返回一個DBObjects數組。
  • 然后,我們將調用以下三種方法,我們將在下面分別進行回顧。
public Step step2(){return stepBuilderFactory.get("step2").tasklet(new Tasklet(){@Overridepublic RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception{// all printing out to console removed for post's brevity// checks if our collection existsBoolean doesexist = mongoTemplate.collectionExists("foo");// show all DBObjects in foo collectionDBCursor alldocs = mongoTemplate.getCollection("foo").find();List<DBObject> dbarray = alldocs.toArray();// execute the three methods we defined for querying the foo collectionString result = doCollect();String resultTwo = doCollectTwo();String resultThree = doCollectThree();return RepeatStatus.FINISHED;}}).build();}

6.1 –第一個查詢

該查詢的目標是找到一個樣式為“ STY_1.1”的文檔。 為此,我們需要記住樣式在文檔中的位置。 它是政策的產物; 因此,我們將其作為Policy.style來處理 。

該查詢的另一個目標是僅返回策略的id字段。 它也是政策的產物。

通過調用以下方法返回結果: mongoTemplate.findOne(query,String.class,“ foo”); 。 輸出為String,因此第二個參數為String.class 。 第三個參數是我們的集合名稱。

public String doCollect(){Query query = new Query();query.addCriteria(Criteria.where("Policy.style").is("STY_1.1")).fields().include("Policy.id");String result = mongoTemplate.findOne(query, String.class, "foo");return result;}

6.2 –第二個查詢

第二個查詢和第一個查詢之間的區別是返回的字段。 在第二個查詢中,我們返回Value,它是Policy和Group的子級。

public String doCollectTwo(){Query query = new Query();query.addCriteria(Criteria.where("Policy.style").is("STY_1.1")).fields().include("Policy.Group.Value");String result = mongoTemplate.findOne(query, String.class, "foo");return result;}

6.3 –第三次查詢

第三個查詢的條件不同。 我們只想返回ID為“ NRD-1”且狀態日期為“ 2017-10-18”的文檔 。 我們只想返回兩個字段:title和description,它們都是Value的子級。

請參閱下面的演示中的XML文檔或打印的JSON,以進一步澄清查詢。

public String doCollectThree(){Query query = new Query();query.addCriteria(Criteria.where("Policy.id").is("NRD-1").and("Policy.status.date").is("2017-10-18")).fields().include("Policy.Group.Value.title").include("Policy.Group.Value.description");String result = mongoTemplate.findOne(query, String.class, "foo");return result;}

7 –Spring批處理作業

作業從步驟1開始,然后調用步驟2。

@Beanpublic Job xmlToJsonToMongo() {return jobBuilderFactory.get("XML_Processor").start(step1()).next(step2()).build();}

8 – @SpringBootApplication

這是一個帶有靜態void main和@SpringBootApplication的標準類。

package com.michaelcgood;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;@SpringBootApplication @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class SpringBatchMongodb {public static void main(String[] args) {SpringApplication.run(SpringBatchMongodb.class, args);} }

9 –演示

9.1 –步驟1

JSON打印為字符串。 由于輸出很長,因此我在下面省略了輸出內容。

Executing step: [step1] PRINTING STRING :::::::::::::::::::::{"Policy": {"Group": {"Value": {"prohibitChanges": true,"description": {

9.2 –步驟2

我剪切了結果以格式化博客文章的輸出。

Executing step: [step2]

檢查集合是否存在

Status of collection returns :::::::::::::::::::::true

顯示所有對象

list of db objects returns:::::::::::::::::::::[{ "_id" : { "$oid" : "59e7c0324ad9510acf5773c0"} , [..]

只需返回Policy的ID

RESULT:::::::::::::::::::::{ "_id" : { "$oid" : "59e7c0324ad9510acf5773c0"} , "Policy" : { "id" : "NRD-1"}}

要查看打印到控制臺的其他結果,請從Github分叉/下載代碼并運行該應用程序。

10 –結論

我們已經審查了如何將XML轉換為JSON,如何將JSON存儲到MongoDB,以及如何在數據庫中查詢特定結果。

進一步閱讀:

  • MongoTemplate
  • JSON.org

源代碼在 Github上

翻譯自: https://www.javacodegeeks.com/2017/10/converting-xml-json-raw-use-mongodb-spring-batch.html

總結

以上是生活随笔為你收集整理的在MongoDB和Spring Batch中将XML转换为JSON和原始使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。