당신은 lxml library를 사용할 수 있습니다. objectify.fromstring
을 사용하여 문자열을 xml 개체로 변환 한 다음 개체 dir 메서드를 찾습니다. 예를 들어 :
from lxml import objectify
xml_string = """<?xml version="1.0" encoding="UTF-8"?><NewOrderResp><IndustryType></IndustryType><MessageType>R</MessageType><MerchantID>700000005894</MerchantID><TerminalID>0031</TerminalID><CardBrand>AMEX</CardBrand><AccountNum>3456732800000010</AccountNum><OrderID>TESTORDER1</OrderID><TxRefNum>55A69B278025130CD36B3A95435AA84DC45363</TxRefNum><TxRefIdx>10</TxRefIdx><ProcStatus>0</ProcStatus><ApprovalStatus>1</ApprovalStatus><RespCode></RespCode><AVSRespCode></AVSRespCode><CVV2RespCode></CVV2RespCode><AuthCode></AuthCode><RecurringAdviceCd></RecurringAdviceCd><CAVVRespCode></CAVVRespCode><StatusMsg></StatusMsg><RespMsg></RespMsg><HostRespCode></HostRespCode><HostAVSRespCode></HostAVSRespCode><HostCVV2RespCode></HostCVV2RespCode><CustomerRefNum>A51C5B2B1811E5991208</CustomerRefNum><CustomerName>BOB STEVEN</CustomerName><ProfileProcStatus>0</ProfileProcStatus><CustomerProfileMessage>Profile Created</CustomerProfileMessage><RespTime>13055</RespTime><PartialAuthOccurred></PartialAuthOccurred><RequestedAmount></RequestedAmount><RedeemedAmount></RedeemedAmount><RemainingBalance></RemainingBalance><CountryFraudFilterStatus></CountryFraudFilterStatus><IsoCountryCode></IsoCountryCode></NewOrderResp>"""
xml_object = objectify.fromstring(xml_string)
print xml_object.__dict__
는 딕셔너리를 반환 딕셔너리에 XML 객체를 변환 : 내가 사용
{'RemainingBalance': u'', 'AVSRespCode': u'', 'RequestedAmount': u'', 'AccountNum': 3456732800000010, 'IsoCountryCode': u'', 'HostCVV2RespCode': u'', 'TerminalID': 31, 'CVV2RespCode': u'', 'RespMsg': u'', 'CardBrand': 'AMEX', 'MerchantID': 700000005894, 'RespCode': u'', 'ProfileProcStatus': 0, 'CustomerName': 'BOB STEVEN', 'PartialAuthOccurred': u'', 'MessageType': 'R', 'ProcStatus': 0, 'TxRefIdx': 10, 'RecurringAdviceCd': u'', 'IndustryType': u'', 'OrderID': 'TESTORDER1', 'StatusMsg': u'', 'ApprovalStatus': 1, 'RedeemedAmount': u'', 'CountryFraudFilterStatus': u'', 'TxRefNum': '55A69B278025130CD36B3A95435AA84DC45363', 'CustomerRefNum': 'A51C5B2B1811E5991208', 'CustomerProfileMessage': 'Profile Created', 'AuthCode': u'', 'RespTime': 13055, 'HostAVSRespCode': u'', 'CAVVRespCode': u'', 'HostRespCode': u''}
는 XML 문자열은 단지 실제 예를 보여 게이트웨이 PAYMENTECH 지불의 응답이다.
또한 위의 예는 재귀 적이 아니므로 dicts 내에 dicts가 있으면 재귀를 수행해야합니다. 난 당신이 사용할 수있는 쓴 재귀 함수를 참조하십시오
을 Heres
from lxml import objectify
def xml_to_dict_recursion(xml_object):
dict_object = xml_object.__dict__
if not dict_object:
return xml_object
for key, value in dict_object.items():
dict_object[key] = xml_to_dict_recursion(value)
return dict_object
def xml_to_dict(xml_str):
return xml_to_dict_recursion(objectify.fromstring(xml_str))
xml_string = """<?xml version="1.0" encoding="UTF-8"?><Response><NewOrderResp>
<IndustryType>Test</IndustryType><SomeData><SomeNestedData1>1234</SomeNestedData1>
<SomeNestedData2>3455</SomeNestedData2></SomeData></NewOrderResp></Response>"""
print xml_to_dict(xml_string)
상위 키/요소를 보존하는 변형 :
def xml_to_dict(xml_str):
""" Convert xml to dict, using lxml v3.4.2 xml processing library, see http://lxml.de/ """
def xml_to_dict_recursion(xml_object):
dict_object = xml_object.__dict__
if not dict_object: # if empty dict returned
return xml_object
for key, value in dict_object.items():
dict_object[key] = xml_to_dict_recursion(value)
return dict_object
xml_obj = objectify.fromstring(xml_str)
return {xml_obj.tag: xml_to_dict_recursion(xml_obj)}
을 그리고 당신은 단지 서브 트리를 반환하고 DICT로 변환하려면 , 당신은) Element.find을 (사용할 수 있습니다
xml_obj.find('.//') # lxml.objectify.ObjectifiedElement instance
는 이러한 목표를 달성하기 위해 많은 옵션이 있습니다하지만 당신은 이미 LXML를 사용하는 경우이 하나가 중대하다. 이 예제에서는 lxml-3.4.2가 사용되었습니다. Cheers!
희망이 도움 : 당신이 그것을 사용하는 방법
이는 다음과 같습니다 유래에 비슷한 질문 다스의 절반을 검토 한 후, 여기에 나를 위해 일한 것입니다 이 질문은 이전에 대답되었습니다 : http://stackoverflow.com/questions/2148119/how-to-convert-an-xml-string-to-a-dictionary-in-python – robjohncox
원하는 출력은 무엇입니까? ? – alecxe
@Josh 나는 당신의 생각 친구를 이해하지 못합니다. – funktasmas