我有一个用Python解析器的嵌套XML。示例
<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来提取元素属性-id=“basketJson”和属性-id=“lastModifiedBasketDate”,任何人都可以帮助我们吗?tks
发布于 2022-11-10 18:19:25
例如,您可以使用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+0000https://stackoverflow.com/questions/74393007
复制相似问题