我有一個嵌套的 XML 來決議 Python。例子
<custom-objects xmlns="http://www.demandware.com/xml/impex/customobject/2006-10-31">
<custom-object type-id="AbandonedBaskets" object-id="b4122d6090d1d6a3f8dafd34b0">
<object-attribute attribute-id="basketJson">{"UUID":"b4122d6090d1d6a3f8dafd34b0"}</object-attribute>
<object-attribute attribute-id="cnRelatedNo">1365</object-attribute>
<object-attribute attribute-id="customerOwnerNo">702069175</object-attribute>
<object-attribute attribute-id="lastModifiedBasketDate">2022-06-29T21:31:04.000 0000</object-attribute>
<object-attribute attribute-id="natg_emailAlreadySent">true</object-attribute>
</custom-object>
我需要創建一個 for 來提取元素 attribute-id="basketJson" 和 attribute-id="lastModifiedBasketDate" 任何人都可以幫助我們嗎?tks
uj5u.com熱心網友回復:
您可以使用例如beautifulsoup決議 XML:
xml_doc = """\
<custom-objects xmlns="http://www.demandware.com/xml/impex/customobject/2006-10-31">
<custom-object type-id="AbandonedBaskets" object-id="b4122d6090d1d6a3f8dafd34b0">
<object-attribute attribute-id="basketJson">{"UUID":"b4122d6090d1d6a3f8dafd34b0"}</object-attribute>
<object-attribute attribute-id="cnRelatedNo">1365</object-attribute>
<object-attribute attribute-id="customerOwnerNo">702069175</object-attribute>
<object-attribute attribute-id="lastModifiedBasketDate">2022-06-29T21:31:04.000 0000</object-attribute>
<object-attribute attribute-id="natg_emailAlreadySent">true</object-attribute>
</custom-object>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(xml_doc, "xml")
for obj in soup.select("custom-object"):
print("basketJson =", obj.select_one('[attribute-id="basketJson"]').text)
print(
"lastModifiedBasketDate =",
obj.select_one('[attribute-id="lastModifiedBasketDate"]').text,
)
印刷:
basketJson = {"UUID":"b4122d6090d1d6a3f8dafd34b0"}
lastModifiedBasketDate = 2022-06-29T21:31:04.000 0000
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532400.html
標籤:Python解析
