Warm tip: This article is reproduced from serverfault.com, please click

How to use the property file or xml file to display data based on the parameter supplied

发布于 2020-11-29 17:24:33

I have property file or xml file which has the following structure:

#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>

I want to write a python/shell script which takes single argument from command line and process the result. I can use any of the property file option or XML based file to fetch the details. For eg. if i pass the argument as dev to the script it should return the connection string value for dev (If I use the property file) or If i use xml file and pass the argument it should return the dev specific username, password, url details and store in 3 new variable.

How can i do this? What is the easiest way to do this? I did inside the python code using variables. But i want to know how to do this with Property file based or xml file based.

Questioner
Subbu
Viewed
0
Jack Fleeting 2020-11-30 22:16:34

I don't know about the properties file, but as far as the xml is concerned you can try this:

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

Output:

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