gpt4 book ai didi

python - 如何在 python 中创建带有标题和正文的 xml

转载 作者:数据小太阳 更新时间:2023-10-29 02:38:18 25 4
gpt4 key购买 nike

我正在尝试将我用 vba 编写的代码重写为 python,以使用 python 生成如下图所示格式的 xml。

示例数据

ORDER_RELEASE_GID       PTA
XXXXXXXXXXX.254687058 15/11/2019
XXXXXXXXXXXXX.8000337937 10/10/2019
XXXXXXXXXXXXX.4501222542 27/9/2019
XXXXXXXXXXXXX.4501221219 1/9/2019
XXXXXXXXXXXXX.4501220248 8/9/2019
XXXXXXXXXXXXX.8000337932
XXXXXXXXXXXXX.8000338393 22/10/2019
XXXXXXXXXXXXX.8000338445 10/9/2019
XXXXXXXXXXXXX.4501221982 9/9/2019
XXXXXXXXXXXXX.256535442 9/9/2019
XXXXXXXXXXXXX.4501220239 1/9/2019
XXXXXXXXXXXXX.4501221187 18/10/2019
XXXXXXXXXXXXX.4501220259 18/10/2019

我的 VBA 代码

Public Const ORDER_ID = "A"
Public Const PTA = "B"
Sub GenerateXML()
Dim i As Integer
Dim row As Long
Dim cur_order As String
Dim xmlFile As String
Dim path As String
Dim oWSS As Object
Dim glogdate As String
Dim StatusDate As Date

Set oWSS = CreateObject("WScript.Shell")
glogdate = Format(Now(), "yyyyMMddhhmmss")
xmlFile = ActiveWorkbook.path & "\xxxxxXXXXX_" & xxxxxxxx& ".xml"
With Worksheets("Sheet1")
row = .Cells(.Rows.Count, "A").End(xlUp).row
End With


i = 2

Open xmlFile For Output As #1

'TRANSMISSION HEADER
Print #1, "<?xml version=" & Chr(34) & "1.0" & Chr(34) & " encoding=" & Chr(34) & "ISO-8859-1" & Chr(34) & "?>"
Print #1, "<Transmission>"
Print #1, " <TransmissionHeader>"
Print #1, " <Version>6.4</Version>"
Print #1, " <TransmissionCreateDt>"
Print #1, " <GLogDate>" & glogdate & "</GLogDate>"
Print #1, " </TransmissionCreateDt>"
Print #1, " <UserName>xxxxxxxxxxxx</UserName>"
Print #1, " <Password>xxxxx</Password>"
Print #1, " <SenderTransmissionNo>xxxxxxxxxxxx_" & glogdate & "</SenderTransmissionNo>"
'Print #1, " <TransmissionType>STAGING</TransmissionType>"
Print #1, " <AckSpec>"
Print #1, " <ComMethodGid>"
Print #1, " <Gid>"
Print #1, " <Xid>EMAIL</Xid>"
Print #1, " </Gid>"
Print #1, " </ComMethodGid>"
Print #1, " <EmailAddress>xxxx.com</EmailAddress>"
Print #1, " <AckOption>ERROR</AckOption>"
Print #1, " </AckSpec>"
Print #1, " </TransmissionHeader>"
Print #1, "<TransmissionBody>"

Do While i <= row


If (Worksheets("Sheet1").Range(PTA & i).Value) = "" Then
i = i + 1
Else

'STATUS
Print #1, " <GLogXMLElement> "
Print #1, " <GenericStatusUpdate> "
Print #1, " <GenericStatusObjectType>ORDER_RELEASE</GenericStatusObjectType> "
Print #1, " <Gid> "
Print #1, " <DomainName>xxx</DomainName> "
Print #1, " <Xid>" & Mid(Worksheets("Sheet1").Range(ORDER_ID & i).Value, 12) & "</Xid> "
Print #1, " </Gid> "
Print #1, " <TransactionCode>U</TransactionCode> "
Print #1, " <Refnum> "
Print #1, " <RefnumQualifierGid> "
Print #1, " <Gid> "
Print #1, " <DomainName>XXXXXXXXXXXXX</DomainName> "
Print #1, " <Xid>XXXXXX</Xid> "
Print #1, " </Gid> "
Print #1, " </RefnumQualifierGid> "
Print #1, " <RefnumValue>" & Format$(Worksheets("Sheet1").Range(PTA & i).Value, "dd-mm-yyyy") & "</RefnumValue> "
Print #1, " </Refnum> "
Print #1, " </GenericStatusUpdate> "
Print #1, " </GLogXMLElement> "

i = i + 1

End If

Loop

Print #1, "</TransmissionBody>"
Print #1, "</Transmission>"
Close #1

End Sub

我尝试编写 Python 代码,但无法像 vba 那样生成自定义 xml。我尝试使用 dicttoxl 和 lxml 函数生成 xml 格式,但无法创建自定义 xml。

如何做到这一点?

我的python代码

df.to_csv('GGG.csv',index=False)
import csv
import lxml.etree as ET

headers = ['ORDER_RELEASE_GID','PTA']

# INITIALIZING XML FILE
root = ET.Element('root')

# READING CSV FILE AND BUILD TREE
with open('GSK.csv') as f:
next(f) # SKIP HEADER
csvreader = csv.reader(f)

for row in csvreader:
data = ET.SubElement(root, "data")
for col in range(len(headers)):
node = ET.SubElement(data, headers[col]).text = str(row[col])

# SAVE XML TO FILE
tree_out = (ET.tostring(root, pretty_print=True, xml_declaration=True, encoding="UTF-8"))

# OUTPUTTING XML CONTENT TO FILE
with open('Output.xml', 'wb') as f:
f.write(tree_out)

最佳答案

这是对您的 VBA 代码的直接翻译:我从 VBA 中获取页眉、正文和页脚输出,并在必要的位置插入格式化值。在处理数据框之前删除空日期行。

header = """<?xml version="1.0" encoding="ISO-8859-1"?>
<Transmission>
<TransmissionHeader>
<Version>6.4</Version>
<TransmissionCreateDt>
<GLogDate>{0}</GLogDate>
</TransmissionCreateDt>
<UserName>user</UserName>
<Password>password</Password>
<SenderTransmissionNo>GSK_PTA_UPLOAD_{0}</SenderTransmissionNo>
<TransmissionType>STAGING</TransmissionType>
<AckSpec>
<ComMethodGid>
<Gid>
<Xid>EMAIL</Xid>
</Gid>
</ComMethodGid>
<EmailAddress>user@example.com</EmailAddress>
<AckOption>ERROR</AckOption>
</AckSpec>
</TransmissionHeader>
<TransmissionBody>
"""

body = """ <GLogXMLElement>
<GenericStatusUpdate>
<GenericStatusObjectType>ORDER_RELEASE</GenericStatusObjectType>
<Gid>
<DomainName>example.com</DomainName>
<Xid>{}</Xid>
</Gid>
<TransactionCode>U</TransactionCode>
<Refnum>
<RefnumQualifierGid>
<Gid>
<DomainName>example.com</DomainName>
<Xid>PTA</Xid>
</Gid>
</RefnumQualifierGid>
<RefnumValue>{}</RefnumValue>
</Refnum>
</GenericStatusUpdate>
</GLogXMLElement>
"""

footer = """</TransmissionBody>
</Transmission>
"""
import pandas as pd
import datetime

//header body footer defined above

df = pd.read_excel('gsk_pta_20190828.xlsm')
df = df.dropna()
glogdate = datetime.datetime.now().strftime('%Y%m%d%H%M%S')

with open('gsk_pta_20190828.xlm', 'w') as f:
f.write(header.format(glogdate))
for row in df.itertuples():
f.write(body.format(row[1][11:], row[2].strftime('%d-%m-%Y')))
f.write(footer)

如果 itertuples 写入每一行对于大文件来说太慢,您可以尝试首先创建一个主体列表,然后将其写入一个函数调用中,如所演示的 here .

关于python - 如何在 python 中创建带有标题和正文的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57839265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com