Store XML Data in a mongodb collection

2020-07-10 05:53发布

问题:

I am still relatively new to NoSQL databases like mongodb, so excuse my ignorance.

Background:

Right now, I have a system that does the following:

  1. gathers system data from clients
  2. outputs that info into an xml document
  3. a perl script takes the data in the xml tags and puts it in a mySQL db.
  4. an apache/php powered website displays the data.

The purpose of this system is to act as an inventory for servers/chassis/network devices/etc.

This has been an okay system, but I have decided to go to a non-relational database because of the advantages I see in using that for the type of data I am storing.

Question:

  1. Is it very simple to extract information from xml documents with mongodb?
  2. Should I rewrite the scripts I have to output a JSON/BSON file instead of XML?
  3. How do you take the information from files and put it into a mongodb database?

回答1:

When moving to a NoSQL document DB, the decision is highly influenced by how the data is read or used by the client/user as the data is mostly pre-aggregated/pre-joined based on the usage patterns. So, technically you can move to mongodb "technically" by just converting the data to json/bson instead of xml while importing the data.



回答2:

  1. MongoDB doesn't support xml document. All documents in mongodb are stored in BSON format.
  2. Yes, you can do that.
  3. Mongodb drivers are available for many languages. Use them.


回答3:

All documents in mongodb are stored in BSON format. You can store xml as a String value to the database. like - {xml : "<root><test>Test XML</test></root>"}



回答4:

In java you can do like this -

TestXML testXML = new TestXML();
        testXML.setXmlKey("test1" + new Date());

        BufferedReader br = new BufferedReader(new FileReader(new File(
                "C:/xml/newxml.xml")));
        String line;
        StringBuilder sb = new StringBuilder();

        while ((line = br.readLine()) != null) {
            sb.append(line.trim());
        }

        testXML.setXmlValue(sb.toString());
        mongoTemplate.save(testXML);

you can read that xml using below java code

List<TestXML> dbObjects = mongoTemplate.findAll(TestXML.class);
        for(TestXML key : dbObjects){
            System.out.println(key.getXmlValue());
        }


标签: xml mongodb