【问题标题】:How does one populate his named tuple from an XML File?如何从 XML 文件中填充他的命名元组?
【发布时间】:2019-12-03 20:18:37
【问题描述】:

我有点卡住了

我想知道如何从 XML 文件中填充我的元组。

这是我目前所拥有的:

from xml.dom import minidom

class Code:
    def __init__(self, ErrorCode, Amount):
        self.ErrorCode = ErrorCode
        self.Amount = Amount


filepath = "D:\V11\Dog"

Codes = (Code('txtPLC_ERROR;A: 16', 0), Code('txtPLC_ERROR;A: 119', 0), Code('txtPLC_ERROR;B: 95', 0))


def readConfig():
    xmldoc = minidom.parse(filepath + '\Config.xml')
    itemlist = xmldoc.getElementsByTagName('item')
#    print(len(itemlist))
#    print(itemlist[0].attributes['name'].value)
    for s in itemlist:
        print("Some Profound text")
        Codes.ErrorCode += s
readConfig()

现在我得到这个错误:

   File "..\PycharmProjects\ProjectX\Analyze.py", line 32, in readConfig
    Codes.Errorcode += s
AttributeError: 'tuple' object has no attribute 'Errorcode'>

请不要因为我很愚蠢就举报这个问题。

【问题讨论】:

  • Codes 是一个包含Code 类对象的元组。 ErrorCodeCode 的属性,而不是元组。 Codes.Errorcode += s 应该做什么?
  • 嗨!它应该在现有元组中添加一个额外的“ErrorCode”

标签: python for-loop tuples populate


【解决方案1】:

Codes.ErrorCode += s 很有道理。 Codes 是一个元组,包含 Code 类的对象。现在,如果您想添加新的 Code 对象,您需要执行类似Codes += Code(string, error_code) 的操作。

但是,Tuples 是不可变的。一旦创建元组,您就无法从元组中添加/删除内容。但是,您可以使用列表。

# codes is a list
Codes = [Code('txtPLC_ERROR;A: 16', 0), Code('txtPLC_ERROR;A: 119', 0), Code('txtPLC_ERROR;B: 95', 0)]

def readConfig():
    xmldoc = minidom.parse(filepath + '\Config.xml')
    itemlist = xmldoc.getElementsByTagName('item')
    for s in itemlist:
        # append a code object to codes
        Codes.append(Code(s, 0))
readConfig()

【讨论】:

  • 为什么是# append a code object to codes?这是OP想要的吗?他有没有在任何地方确认过?
  • “我想知道如何从 XML 文件中填充我的元组”——我猜。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多