简体   繁体   中英

Read simple XML file using python

I'm trying to get publish date from XML file. please see my xml file.

<sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/sdnList.xsd">
  <publshInformation>
    <Publish_Date>06/10/2021</Publish_Date>
    <Record_Count>8954</Record_Count>
  </publshInformation>
</sdnList>

I'm trying below way but its not working and I don't want to use for loop for simple file. Thanks

import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")
root = tree.getroot()

publish_Date = root.findall("Publish_Date")

for pdate in publish_Date:
   print(pdate.text)

You need to use the namespace. see below

import xml.etree.ElementTree as ET

xml = '''<sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/sdnList.xsd">
 <publshInformation>
   <Publish_Date>06/10/2021</Publish_Date>
   <Record_Count>8954</Record_Count>
 </publshInformation>
</sdnList>'''


root = ET.fromstring(xml)
print(root.find('.//{http://tempuri.org/sdnList.xsd}Publish_Date').text)

output

06/10/2021

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM