search
HomeBackend DevelopmentXML/RSS TutorialPython parses xml[xml.dom]

Python parses xml[xml.dom]

Feb 25, 2017 pm 02:21 PM

Requirements

There is a table with a large amount of data, which is updated every day. Its fields can be configured through the xml configuration file, that is, the fields may be different every time the table is created. When running upstream, it will be extracted from the source file according to the configuration. In the step of warehousing, the table needs to be built according to the configuration.

Solution

Write a simple xml, configure the required fields and types to read the corresponding data upstream and put it into the database. First delete the original table and create a new table according to the configuration

XML file

name="top_query" db_name="evaluting_sys">
id
query
varchar(200)
false
query
pv
integer
false
pv
avg_money
integer
false

Processing script

#!/usr/bin/python
# 
-*- coding:utf-8 -*-
#author: 
wklken
#desc: 
use to read db xml config.
#-----------------------
#2012-02-18 
created
#----------------------
import sys,os
from xml.dom import minidom, Node
def read_dbconfig_xml(xml_file_path):
content = {}
root = minidom.parse(xml_file_path)
table = root.getElementsByTagName("table")[0]
#read dbname and table name.
table_name = table.getAttribute("name")
db_name = table.getAttribute("db_name")
if len(table_name) > 0 and len(db_name) > 0:
db_sql = "create database if not exists `" + db_name +"`; use " + db_name + ";"
table_drop_sql = "drop " + table_name + " if exists " + table_name + ";"
content.update({"db_sql" : db_sql})
content.update({"table_sql" : table_drop_sql })
else:
print "Error:attribute is not define well! db_name=" + db_name + " ;table_name=" + table_name
sys.exit(1)
#print table_name, db_name
table_create_sql = "create table " + table_name +"("
#read primary cell
primary_key = table.getElementsByTagName("primary_key")[0]
primary_key_name = primary_key.getElementsByTagName("name")[0].childNodes[0].nodeValue
table_create_sql += primary_key_name + " INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,"
#print primary_key.toxml()
#read ordernary field
fields = table.getElementsByTagName("field")
f_index = 0
for field in fields:
f_index += 1
name = field.getElementsByTagName("name")[0].childNodes[0].nodeValue
type = field.getElementsByTagName("type")[0].childNodes[0].nodeValue
table_create_sql += name + " " + type
if f_index != len(fields):
table_create_sql += ","
is_index = field.getElementsByTagName("is_index")[0].childNodes[0].nodeValue
table_create_sql += ");"
content.update({"table_create_sql" : table_create_sql})
#character set latin1 collate latin1_danish_ci;
print content
if __name__ == "__main__":
read_dbconfig_xml(sys.argv[1])

Involved methods

root = minidom.parse(xml_file_path) Get the dom object

root.getElementsByTagName( "table") Get the node list based on tag

table.getAttribute("name") Get the attribute

primary_key.getElementsByTagName("name")[0].childNodes[0].nodeValue Get the value of the child node (id gets id)

The above is the content of Python parsing xml[xml.dom]. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor