在Python中构建通用XML解析器?

时间:2016-02-03 07:07:02

标签: python xml parsing elementtree celementtree

我是一名新手,有一周的编写python脚本的经验。

我正在尝试编写一个通用解析器(用于我所有未来作业的库),它解析任何输入XML,而不需要任何先前的标记知识。

  • 解析输入XML。
  • 从XML中获取值并根据标记设置值。
  • 在作业的其余部分使用这些值。

我正在使用“xml.etree.ElementTree”库,我能够以下面提到的方式解析XML。

#!/usr/bin/python

import os
import xml.etree.ElementTree as etree
import logging


logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.info('start reading XML property file')
filename = "mood_ib_history_parameters_DEV.xml"

logger.info('getting the current location')
__currentlocation__ = os.getcwd()
__fullpath__ = os.path.join(__currentlocation__,filename)

logger.info('start parsing the XML property file')
tree = etree.parse(__fullpath__)
root = tree.getroot()

hive_db = root.find("hive_db").text
EDGE_HIVE_CONN = root.find("EDGE_HIVE_CONN").text
target_dir = root.find("target_dir").text
to_email_alias = root.find("to_email_alias").text
to_email_cc = root.find("to_email_cc").text
from_email_alias = root.find("from_email_alias").text
dburl = root.find("dburl").text
SQOOP_EDGE_CONN = root.find("SQOOP_EDGE_CONN").text
user_name = root.find("user_name").text
password = root.find("password").text
IB_log_table = root.find("IB_log_table").text
SR_DG_master_table = root.find("SR_DG_master_table").text
SR_DG_table = root.find("SR_DG_table").text

logger.info('Hive DB %s', hive_db)
logger.info('Hive DB %s', hive_db)
logger.info('Edge Hive Connection %s', EDGE_HIVE_CONN)
logger.info('Target Directory %s', target_dir)
logger.info('To Email address %s', to_email_alias)
logger.info('CC Email address %s', to_email_cc)
logger.info('From Email address %s', from_email_alias)
logger.info('DB URL %s',dburl)
logger.info('Sqoop Edge node connection %s',SQOOP_EDGE_CONN)
logger.info('Log table name %s',IB_log_table)
logger.info('Master table name %s',SR_DG_master_table)
logger.info('Data governance table name %s',SR_DG_table)

现在的问题是,如果我想在不知道标签和元素的情况下解析XML,并使用值我该怎么做。我已经完成了多个教程,但所有这些教程都帮助我使用下面的标签解析XML

SQOOP_EDGE_CONN = root.find("SQOOP_EDGE_CONN").text

任何人都可以指向正确的教程或库或代码片段来动态解析XML。

2 个答案:

答案 0 :(得分:0)

我认为官方文档非常清晰,并包含一些示例:https://docs.python.org/3/library/xml.etree.elementtree.html

您需要实现的主要部分是循环子节点(可能是递归的):

for child in root:
    # child.tag contains the tag name, child.attrib contains the attributes
    print(child.tag, child.attrib)

答案 1 :(得分:0)

解析很简单 - etree.parse(path)

使用tree.getroot()获得root后,您可以使用Python的“in”迭代树:

for child_node in tree.getroot():
   print child_node.text

然后,要查看这些child_node的标签,您可以使用相同的技巧。 这使您可以遍历XML中的所有标记,而无需知道标记名称。

相关问题