I am having trouble extracting (name, value) pair from XML where name == 'mykey', using Python's xml.etree.ElementTree library. The pseudo-code I want is:
if (name.text == 'mykey'):
print value.text
Value would be the value of mykey which in this example case is XX111.
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE charles-session SYSTEM "https://www.charlesproxy.com/dtd/charles-session-1_2.dtd">
<charles-session>
<header>
<name>Content-Length</name>
<value>10804</value>
</header>
<header>
<name>Date</name>
<value>Wed, 13 Oct 2021 22:02:42 GMT</value>
</header>
<header>
<name>mykey</name>
<value>XX111</value>
</header>
<header>
<name>Accept-Language</name>
<value>en-US;q=1.0, el-US;q=0.9</value>
</header>
I can get the 'mykey' text printed, but I don't know how to say "now give me the text of the value right after 'mykey'.
for name in root_node.iter('name'):
if re.match(r'mykey', name.text):
print(name.text)
CodePudding user response:
Get the element value and line number this element is at.
Please look at the comment on code for explanation:
# Data setup
from io import StringIO
xml_data="""\
<?xml version="1.0" encoding="UTF-8"?>
<charles-session>
<header>
<name>Content-Length</name>
<value>10804</value>
</header>
<header>
<name>Date</name>
<value>Wed, 13 Oct 2021 22:02:42 GMT</value>
</header>
<header>
<name>mykey</name>
<value>XX111</value>
</header>
<header>
<name>Accept-Language</name>
<value>en-US;q=1.0, el-US;q=0.9</value>
</header>
</charles-session>
"""
now get the element looking for and its value.
# define the root
root = ET.parse(StringIO(xml_data)).getroot()
# based on xpath get the key and its value
for each in root.findall(".//header"):
if "mykey" in each[0].text:
print(each[1].text)