【问题标题】:How to use the property file or xml file to display data based on the parameter supplied如何使用属性文件或xml文件根据提供的参数显示数据
【发布时间】:2020-11-29 17:24:33
【问题描述】:

我有具有以下结构的属性文件或 xml 文件:

#conf.properties
DEV="jdbc:oracle:thin:@devHost:1521:ORCL"
QA="jdbc:oracle:thin:@qaHost:1521:ORCL"


#db_conf.xml
<?xml version="1.0"?>
<environments>
    <env name="Dev">
        <username>oracle</username>
        <password>welcome</password>
        <url>devHost:1521</url>
    </env>
    <env name="QA">
        <username>oracle</username>
        <password>welcome</password>
        <url>qaHost:1525</url>
    </env>
</environments>

我想编写一个 python/shell 脚本,它从命令行获取单个参数并处理结果。我可以使用任何属性文件选项或基于 XML 的文件来获取详细信息。 例如。如果我将参数作为 dev 传递给脚本,它应该返回 dev 的连接字符串值(如果我使用属性文件) 或者 如果我使用 xml 文件并传递参数,它应该返回 dev 特定的用户名、密码、url 详细信息并存储在 3 个新变量中。

我该怎么做?最简单的方法是什么?我在 python 代码中使用了变量。但我想知道如何使用基于属性文件或基于 xml 文件来做到这一点。

【问题讨论】:

  • 看看使用xmllint

标签: python xml shell unix


【解决方案1】:

我不知道属性文件,但就xml而言,你可以试试这个:

from lxml import etree

conf = """[your xml above]"""
input = "Dev"

doc = etree.XML(conf)
# to load from a file, try: etree.parse(r'path_to_file\file_name.xml')
spath = f"//env[@name='{input}']"
#the above uses f-strings to create the xpath search expression: see https://realpython.com/python-f-strings/
for dev in doc.xpath(spath):
    u_name = dev.xpath('./username/text()')[0]
    pw = dev.xpath('./password/text()')[0]
    url= dev.xpath('./url/text()')[0]
u_name,pw,url

输出:

('oracle', 'welcome', 'devHost:1521')

【讨论】:

  • 谢谢。如何在这个程序中导入外部xml文件?以及如何为未找到元素的情况添加功能? "f"//env[@name='{input}']"" 行是做什么的?
  • @Subbu 在编辑后的答案中查看新的 cmets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多