【问题标题】:Changing the value of an XML element with ElementTree gives out TypeError使用 ElementTree 更改 XML 元素的值会导致 TypeError
【发布时间】:2022-07-05 23:25:55
【问题描述】:

我正在解析 .csv 文件中的值,以便编辑 .xml 文件的值以进行 HTTP 发布。代码运行良好。

工作 .csv 代码:

with open("mail_data.csv", 'r') as file:        
        csvreader = csv.reader(file)
        for row in csvreader:
            if row[7] == "YES":
                root.find('RCPT_LIST/RCPT/TA').text = row[0]

现在,我想直接从 .xlsx 文件中解析值,所以我使用 openpyxl 来复制我对 csv 所做的操作。但是,下面的代码给出了TypeError: argument should be integer or bytes-like object, not 'str'

for row in sheet.iter_rows(min_row=2):
            root.find('RCPT_LIST/RCPT/TA').text = row[3].value

打印root.find('RCTP_LIST/RCPT/TA').textrow[3].value 会给出正确的信息,因此我不知道如何解决它。我没有改变任何关于如何解析 XML 文件的内容,即:

tree = ET.parse(xml_name)
root = tree.getroot()

编辑后,我使用ET.tostring(root) 将其添加为HTTP Post 的有效负载。提前致谢。

【问题讨论】:

  • 你可以试试我的答案,如果它有效,请告诉我

标签: python xml elementtree python-3.10


【解决方案1】:

它需要一个类似对象的字节

试试:

root.find(b'RCPT_LIST/RCPT/TA').text = row[3].value

【讨论】:

  • 我在添加 b 时得到了TypeError: cannot use a string pattern on a bytes-like object
  • 试试root.find(bytes('RCPT_LIST/RCPT/TA', encoding='utf8')).text = row[3].value
猜你喜欢
  • 2017-07-30
  • 1970-01-01
  • 2019-06-17
  • 2018-08-27
  • 2018-04-12
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
相关资源
最近更新 更多