Как добавить тег в XML?
Есть код который обрабатывает файлы в определенном фолдере. из каждого файла значения передаются в функцию send_to_t24
в свою очередь эта функция отправляет запрос и получает ответ в виде xml и записывает его в файл как сделать так чтобы в xml добавлялись и имена обрабатываемых файлов?
def send_to_t24(card):
url = "http://xxxx.xx:8900"
header = {"content-type": "text/xml"}
body = """
<soapenv:Envelope xmlns:soapenv="http://xxxx.xx:8900"
<soapenv:Header/>
<soapenv:Body>
<car:PinTabrequest>
<WebRequestCommon>
<company>1</company>
<password>Q1</password>
<userName>O</userName>
</WebRequestCommon>
<PINTABREQUESTType>
<enquiryInputCollection>
<columnName>PAN</columnName>
<criteriaValue>CARD</criteriaValue>
<operand>EQ</operand>
</enquiryInputCollection>
<enquiryInputCollection>
</enquiryInputCollection>
</PINTABREQUESTType>
</car:PinTabrequest>
</soapenv:Body>
</soapenv:Envelope>
"""
convert = open("fileFromT24.xml", "a+")
post_data = body.replace("CARD", str(card))
sendrequest = requests.post(url, data=post_data, headers=header)
print(sendrequest.text, file=convert)
convert.close()
XML выглядит так:
<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:PinTabrequestResponse xmlns:ns2="http://temenos.com/CardPinTabRequest"><Status><successIndicator>Success</successIndicator></Status><PINTABREQUESTType><gPINTABREQUESTDetailType><mPINTABREQUESTDetailType><CardNumber>6612644511582146</CardNumber><ContractType>Yes</ContractType><CardNumber2></CardNumber2><NameSurname>VOLKOVA</NameSurname><PersonalCode>1</PersonalCode><CustomerId>9</CustomerId><UserNameSurname></UserNameSurname><UserPersonalCode></UserPersonalCode><UserCustomerId></UserCustomerId><Language>2</Language><Residence>LV</Residence><Street>BULVARIS 60-15</Street><KeyPhrase>E</KeyPhrase><Sector>6000</Sector><AccountOfficer>762</AccountOfficer><Sex>2</Sex><RemoteServices></RemoteServices><PasportNumber>329</PasportNumber><PassportExpire>20</PassportExpire><PhoneNumber></PhoneNumber><MobileNumber>5</MobileNumber></mPINTABREQUESTDetailType></gPINTABREQUESTDetailType></PINTABREQUESTType></ns2:PinTabrequestResponse></S:Body></S:Envelope>
Результат
<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:PinTabrequestResponse xmlns:ns2="http://temenos.com/CardPinTabRequest"><Status><successIndicator>Success</successIndicator></Status><PINTABREQUESTType><gPINTABREQUESTDetailType><mPINTABREQUESTDetailType><CardNumber>6612644511582146</CardNumber><ContractType>Yes</ContractType><CardNumber2></CardNumber2><NameSurname>VOLKOVA</NameSurname><PersonalCode>1</PersonalCode><CustomerId>9</CustomerId><UserNameSurname></UserNameSurname><UserPersonalCode></UserPersonalCode><UserCustomerId></UserCustomerId><Language>2</Language><Residence>LV</Residence><Street>BULVARIS 60-15</Street><KeyPhrase>E</KeyPhrase><Sector>6000</Sector><AccountOfficer>762</AccountOfficer><Sex>2</Sex><RemoteServices></RemoteServices><PasportNumber>329</PasportNumber><PassportExpire>20</PassportExpire><PhoneNumber></PhoneNumber><MobileNumber>5</MobileNumber><CTX_files>ctx_files</CTX_files></mPINTABREQUESTDetailType></gPINTABREQUESTDetailType></PINTABREQUESTType></ns2:PinTabrequestResponse></S:Body></S:Envelope>
Ответы (1 шт):
Добавил пример парсинга XML, нахождения определенного тега mPINTABREQUESTDetailType и добавления в него нового тега CTX_files
Пример:
import xml.etree.ElementTree as ET
text = """\
<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:PinTabrequestResponse xmlns:ns2="http://temenos.com/CardPinTabRequest"><Status><successIndicator>Success</successIndicator></Status><PINTABREQUESTType><gPINTABREQUESTDetailType><mPINTABREQUESTDetailType><CardNumber>6612644511582146</CardNumber><ContractType>Yes</ContractType><CardNumber2></CardNumber2><NameSurname>VOLKOVA</NameSurname><PersonalCode>1</PersonalCode><CustomerId>9</CustomerId><UserNameSurname></UserNameSurname><UserPersonalCode></UserPersonalCode><UserCustomerId></UserCustomerId><Language>2</Language><Residence>LV</Residence><Street>BULVARIS 60-15</Street><KeyPhrase>E</KeyPhrase><Sector>6000</Sector><AccountOfficer>762</AccountOfficer><Sex>2</Sex><RemoteServices></RemoteServices><PasportNumber>329</PasportNumber><PassportExpire>20</PassportExpire><PhoneNumber></PhoneNumber><MobileNumber>5</MobileNumber></mPINTABREQUESTDetailType></gPINTABREQUESTDetailType></PINTABREQUESTType></ns2:PinTabrequestResponse></S:Body></S:Envelope>
"""
root = ET.fromstring(text)
detail_type_el = root.find('.//mPINTABREQUESTDetailType')
ctx_files = r"C:\foo\abc\123.xml"
ctx_files_el = ET.Element('CTX_files')
ctx_files_el.text = ctx_files
detail_type_el.append(ctx_files_el)
xml_bytes = ET.tostring(root, encoding="utf-8", xml_declaration=True)
with open("fileFromT24.xml", 'wb') as f:
f.write(xml_bytes)
Если нужно именно добавлять в файл, как ранее до этого делали, тогда вместо wb используйте ab+. Можно оставить и a+, но нужно будет из байтов в xml_bytes получить строку xml_bytes.decode('utf-8')
Добавил пример кода на коде из вопроса, постарался сохранить максимум логики старого кода:
import xml.etree.ElementTree as ET
def send_to_t24(card, ctx_files: str):
url = "http://xxxx.xx:8900"
header = {"content-type": "text/xml"}
body = """
<soapenv:Envelope xmlns:soapenv="http://xxxx.xx:8900"
<soapenv:Header/>
<soapenv:Body>
<car:PinTabrequest>
<WebRequestCommon>
<company>1</company>
<password>Q1</password>
<userName>O</userName>
</WebRequestCommon>
<PINTABREQUESTType>
<enquiryInputCollection>
<columnName>PAN</columnName>
<criteriaValue>CARD</criteriaValue>
<operand>EQ</operand>
</enquiryInputCollection>
<enquiryInputCollection>
</enquiryInputCollection>
</PINTABREQUESTType>
</car:PinTabrequest>
</soapenv:Body>
</soapenv:Envelope>
"""
post_data = body.replace("CARD", str(card))
sendrequest = requests.post(url, data=post_data, headers=header)
text_xml = sendrequest.text
root = ET.fromstring(text_xml)
detail_type_el = root.find('.//mPINTABREQUESTDetailType')
ctx_files_el = ET.Element('CTX_files')
ctx_files_el.text = ctx_files
detail_type_el.append(ctx_files_el)
xml_bytes = ET.tostring(root, encoding="utf-8", xml_declaration=True)
text_xml = xml_bytes.decode('utf-8')
convert = open("fileFromT24.xml", "a+")
print(text_xml, file=convert)
convert.close()
...
for value in read_file_ctx():
ctx_files = value
# csv_files = str(value).replace(".ctx", ".csv")
with open(ctx_files, errors='ignore') as crd:
for line in crd:
if "%B" in line:
card = line[9:25]
# print(line[9:25])
send_to_t24(card, ctx_files)