0% found this document useful (0 votes)
4 views1 page

xml.py

The document is a Python script that connects to a MongoDB database and reads an XML file. It converts the XML data into a dictionary format and inserts it into a specified MongoDB collection. Finally, it retrieves and prints all documents from the collection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

xml.py

The document is a Python script that connects to a MongoDB database and reads an XML file. It converts the XML data into a dictionary format and inserts it into a specified MongoDB collection. Finally, it retrieves and prints all documents from the collection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

from pymongo import MongoClient

import xml.etree.ElementTree as ET
import pymongo
import json
# Replace the connection string with your MongoDB connection string
client =
pymongo.MongoClient("mongodb+srv://palanikalyan:[email protected]
u22a.mongodb.net/?retryWrites=true&w=majority")

# Replace "mydatabase" with the name of your database


db = client.get_database("kalyan")
# Replace "mycollection" with the name of your collection
collection = db.qwerty# Read the JSON document from a file
# Read the XML file and parse it into an ElementTree object
xml_file = "C:\sample_CustomersOrders.xml"
xml_tree = ET.parse(xml_file)

# Convert the ElementTree object into a dictionary


def element_to_dict(element):
"""Convert an ElementTree element to a dictionary"""
dict_ = {}
if element.attrib:
dict_["attributes"] = element.attrib
if element.text:
dict_["text"] = element.text
for child in element:
dict_.setdefault(child.tag, []).append(element_to_dict(child))
return dict_

xml_dict = element_to_dict(xml_tree.getroot())

# Insert the XML document into the collection


collection.insert_one(xml_dict)

# Find all documents


documents = collection.find()

# Print all documents


for document in documents:
print(document)

You might also like