Python if语句,不能连接'str'和'instance'对象

Gil*_*t V 2 python if-statement xml-parsing

我的问题是我想检查一个被调用的xml变量中的变量xmlauthor,我想检查是否基本上写了一些东西.我该怎么办?这是我到目前为止所写的:

for num in ic : 
    xmlauthor = dom.getElementsByTagName("author")[0]

    if not xmlauthor: 
        content += "***Changes by:"  + xmlauthor + "*** \n \n"
    else:
        content += "***Changes are made Anonumously** \n \n" 
Run Code Online (Sandbox Code Playgroud)

这是我在控制台上遇到的错误

content += "***Changes by:"  + xmlauthor + "*** \n\n" 
TypeError: cannot concatenate 'str' and 'instance' objects
Run Code Online (Sandbox Code Playgroud)

Dav*_*son 8

假设您正在使用xml.dom:getElementsByTagName它不返回字符串列表,它返回一个Element对象列表,因此您无法连接xmlauthor到该行中的字符串

    content += "***Changes by:"  + xmlauthor + "*** \n \n"
Run Code Online (Sandbox Code Playgroud)

您可以通过将其更改为以下内容将其转换为字符串:

    content += "***Changes by:"  + xmlauthor.childNodes[0].nodeValue + "*** \n \n"
Run Code Online (Sandbox Code Playgroud)

  • 可能需要像`xmlauthor.childNodes [0] .nodeValue`这样的东西. (2认同)