【问题标题】:Building a generic XML parser in Python?在 Python 中构建通用 XML 解析器?
【发布时间】:2016-02-03 07:07:01
【问题描述】:

我是新手,有 1 周的 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

谁能给我一个正确的教程或库或代码 sn-p 来动态解析 XML。

【问题讨论】:

  • 您是否需要parsing - 从 xml 文件创建 etree - 或 searching - 在 etree 中查找元素? etree 具有除find 之外的其他功能。

标签: python xml parsing elementtree celementtree


【解决方案1】:

我认为官方文档很清楚,并包含一些示例: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)

【讨论】:

    【解决方案2】:

    解析就这么简单-etree.parse(path)

    一旦您使用tree.getroot() 获得了根,您就可以使用 Python 的“in”遍历树:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 2013-06-30
      • 1970-01-01
      • 2012-05-02
      • 2010-12-08
      • 1970-01-01
      • 2017-08-01
      相关资源
      最近更新 更多