如何使用 xml.etree 从 xml url 中提取一个值

How to extract one value from an xml url using xml.etree

我正在尝试打印 XML 树的一个字段的值,这里是 XML 树(例如),当我请求它时得到的那个

<puco>
    <resultado>OK</resultado>
    <coberturaSocial>O.S.P. TIERRA DEL FUEGO(IPAUSS)</coberturaSocial>
    <denominacion>DAMIAN GUTIERREZ DEL RIO</denominacion>
    <nrodoc>32443324</nrodoc>
    <rnos>924001</rnos>
    <tipodoc>DNI</tipodoc>
</puco>

现在,我只想打印 "coberturaSocial" 值,这里是我在 views.py 中的请求:

def get(request):
    r = requests.get('https://sisa.msal.gov.ar/sisa/services/rest/puco/38785898')
    dom = r.content
    asd = etree.fromstring(dom)

如果我打印 "asd" 我得到这个错误:视图没有 return HttpResponse 对象。它 return 改为 None。 而且在控制台中我得到了这个 我只想打印 coberturaSocial,请帮忙,xml 解析中的新功能!

您需要提取标签的内容,然后 return 将其包裹在响应中,如下所示:

return HttpResponse(asd.find('coberturaSocial').text)

我猜 etreeimport xml.etree.ElementTree as etree

您可以使用:

text = r.content
dom = etree.fromstring(text)
el = dom.find('coberturaSocial')
el.text # this is where the string is