![](/img/trans.png)
[英]Detect and control the creation of self-closing xml elements in Python?
[英]Python: Extract attributes from a self-closing element with same name as other elements
我需要從一些包含相同名稱元素的XML中提取一些屬性值(很抱歉,我不太了解XML術語)。
我一直在使用xml.etree.ElementTree庫的xpath解析,但是我一直在獲取空值。
這是XML的示例:
<parent>
<child tag1="spam" tag2="1" tag3="some url" />
<child tag1="spam" tag2="2" tag3="another url" />
<child tag1="spam" tag2="3" tag3="yet another url" />
<child tag1="spam" tag2="4" tag3="the last url" />
我正在嘗試從第3個子標記中提取網址,其中tag2 =“ 3”
import xml.etree.ElementTree as ET
r=requests.get(url, user, password) #from another .py file I made for this use
tree=ET.fromstring(r.content)
desired_out=tree.findall('.//child/..[@tag2="3"]')
print(desired_out)
當我嘗試提取XML時,requests.get執行適用於XML中的所有其他字段,但是xpath似乎有問題。
預期的輸出應該是URL,或者至少是它存儲在內存中的某種指示,而不是[]。
感謝您的任何幫助。
我把它整理好了。 無論出於什么原因,xpath選項都不適合我,因此我只做了一些for循環和if語句來獲取所需的內容。
```python
for lmnt in root.findall(parent, namespace):
for grandchild in lmnt.findall(child, namespace):
tags = grandchild.attrib[tag2_attrib]
if tags == '3':
url = grandchild.attrib[tag3_attrib]
```
以字符串格式返回URL。 不過,感謝您的答復,感謝您的答復。
使用這個xpath
.//child[@tag2="3"]/@tag3
另一種方法是使用xmltodict將XML轉換為dict
:
import xmltodict
data = '''<parent>
<child tag1="spam" tag2="1" tag3="some url" />
<child tag1="spam" tag2="2" tag3="another url" />
<child tag1="spam" tag2="3" tag3="yet another url" />
<child tag1="spam" tag2="4" tag3="the last url" />
</parent>'''
result = xmltodict.parse(data)['parent']['child'][2]['@tag3']
輸出:
yet another url
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.