-2

I'm new here and also new to python so I'm struggling with a simple task that i hope you can help me with.

I have a text file that contains data in the following format:

<add key="DateFormat" value="dd-MMM-yyyy"/>
<add key="JsDateFormat" value="DD-MMM-YYYY"/>
<add key="dbDateFormat" value="dd-MMM-yyyy HH:mm:ss:fff"/>

What I want to do is to read and print the lines that contain certain keys, for example DateFormat and dbDateFormat and print their values.

I am reading files using:

f = open("file.config", "r")
file = f.read()
print(file)

It reads the whole file as expected, but I don't know how to make it search and print with the conditions described above.

I will highly appreciate any help.

Jones1220
  • 786
  • 2
  • 11
  • 22
Bartosz C
  • 3
  • 2
  • Check out https://docs.python.org/3/library/xml.etree.elementtree.html. – Henning Koehler Nov 06 '18 at 11:34
  • Possible duplicate of [Print line containing "word" python](https://stackoverflow.com/questions/13905101/print-line-containing-word-python) – tripleee Nov 06 '18 at 11:36
  • Possible duplicate of https://stackoverflow.com/questions/33657794/read-line-in-file-print-line-if-it-contains-string – tripleee Nov 06 '18 at 11:36
  • And etc; what did you search for, what did you find; why didn't it work for you? – tripleee Nov 06 '18 at 11:37
  • Possible duplicate of [How do I parse XML in Python?](https://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python) – Netwave Nov 06 '18 at 11:40

2 Answers2

0

First you need to check if the document is a proper XML file or not. Your example content will raise parse error if I read using lxml library. So it is needed to be fixed at first. The following nodes must be children of a root node. Let's assume the root node is <body>.

from lxml import etree

text="""
<body>
<add key="DateFormat" value="dd-MMM-yyyy"/>
<add key="JsDateFormat" value="DD-MMM-YYYY"/>
<add key="dbDateFormat" value="dd-MMM-yyyy HH:mm:ss:fff"/>
</body>
"""

parsed = etree.fromstring(text)

# Now applying xpath to get value

print(parsed.xpath("//add[@key='DateFormat']/@value"))

# Which outputs to ['dd-MMM-yyyy']

You can use or xpath expression to get values from the keys you want .

Manash Mandal
  • 421
  • 2
  • 5
0

Thanks for an answer, i handled it with a simple for / if loop and parsed text strings, thanks anyway!

Bartosz C
  • 3
  • 2