from xml.etree import ElementTree as ET
s2 = """<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="_0">
<u:Created>2020-11-19T19:01:30.066Z</u:Created>
<u:Expires>2020-11-19T19:06:30.066Z</u:Expires>
</u:Timestamp>
</o:Security>
</s:Header>
<s:Body>
<GetStatusOfTicketResponse xmlns="https://pl"
xmlns:a="http://schemas.datacontract.org/2004/07/Webservice.Domain.Beans.Tickets"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Ticket>DodajKarty_101</a:Ticket>
<a:InfoStatus>
<Code>05300001</Code>
<Message>Podany ticket nie istnieje w systemie</Message>
<Status>ERROR</Status>
</a:InfoStatus>
</GetStatusOfTicketResponse>
</s:Body>
</s:Envelope>
"""
tree = ET.fromstring(s2)
print(tree)
print("tag: ", tree.tag)
print('attrib: ', tree.attrib)
ns = {'a': "http://schemas.datacontract.org/2004/07/Webservice.Domain.Beans.Tickets"}
print("Ticket: ", tree.find('.//{http://schemas.datacontract.org/2004/07/Webservice.Domain.Beans.Tickets}Ticket').text)
#Ticket: DodajKarty_101 #Is accessible
但当我想访问此部分时:
<a:Ticket>DodajKarty_101</a:Ticket>
<a:InfoStatus>
<Code>05300001</Code>
<Message>Podany ticket nie istnieje w systemie</Message>
<Status>ERROR</Status>
</a:InfoStatus>
</GetStatusOfTicketResponse>
print("InfoStatus: ", tree.find('.//{http://schemas.datacontract.org/2004/07/Webservice.Domain.Beans.Tickets}InfoStatus').text)
print("Message: ", tree.find('.//a:InfoStatus', ns).text)
print("InfoStatus: ", tree.find('.//InfoStatus').text)
print("Code: ", tree.find('.//InfoStatus/Code').text)
我被错误缠住了。我在dochttps://docs.python.org/3.4/library/xml.etree.elementtree.html中查找了一些示例,它们正在我的机器上工作。但是,当我试图将这些知识应用到我的XML中时,我开始提取“代码”、“消息”和“状态”
当我使用另一个包来解析XML(如xmltodict)时,我没有问题,但我的下一个目标是在XML中放置一个新的子对象来创建新的响应,因此我需要使用XML.etree来解决这个问题
traceback (most recent call last):
File ".\addingChildsToXML.py", line 43, in <module>
print("InfoStatus: ", tree.find('.//InfoStatus').text)
AttributeError: 'NoneType' object has no attribute 'text'
有几种方法可以解决这个问题,这里有一种:
输出:
相关问题 更多 >
编程相关推荐