[英]Beautiful Soup parsing an XML file
我正在使用Beautiful Soup編寫一個簡單的Python,以從xml文件中解析出我需要的數據。 我需要它正在起作用,但是我想問一下大家,因為我嘗試使用Google進行搜索,但似乎找不到我想要的東西。
XML字符串樣本:
<ProductAttribute MaintenanceType="C" AttributeID="Attachment Type" PADBAttribute="N" RecordNumber="1" LanguageCode="EN">Clamp-On</ProductAttribute>
我需要ProductAttribute中的AttributeID 。 當我寫時,下面我可以獲取值“ Clamp-On”,但是我需要AttributeID告訴我Clamp-On引用了什么。
attributes[part.find('PartNumber').get_text()] = [x.get_text() for x in part.find_all('ProductAttribute')]
for key, value in attributes.items():
for v in value:
print(v)
任何指導意見都應先於負面反饋。 謝謝!
這是您可以使用BeautifulSoup和lxml從xml獲取標簽屬性的方法,
from bs4 import BeautifulSoup
xml_string = '<ProductAttribute MaintenanceType="C" AttributeID="Attachment Type" PADBAttribute="N" RecordNumber="1" LanguageCode="EN">Clamp-On</ProductAttribute>'
soup = BeautifulSoup(xml_string, 'xml')
tag = soup.ProductAttribute
print(tag['AttributeID'])
此代碼打印屬性AttributeID
的值
僅使用lxml
庫的簡單解決方案:
from lxml import etree
xml_string = """<ProductAttribute MaintenanceType="C" AttributeID="Attachment Type" PADBAttribute="N" RecordNumber="1" LanguageCode="EN">Clamp-On</ProductAttribute>"""
xml = etree.XML(xml_string)
print(xml.get("AttributeID"))
輸出 :
Attachment Type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.