jjzjj

xml - 属性错误 : type object 'ElementTree' has no attribute 'tostring'

coder 2024-06-24 原文

我有这个问题,AttributeError: type object 'ElementTree' has no attribute 'tostring',我不知道出了什么问题,我导入到字符串,它不起作用。 尝试按照另一个教程进行操作,但是什么也没有。

有没有其他方法可以将 ElementTree 对象转换为 XML 字符串?

import os
import re
import glob
from xml.dom import minidom
from time import strftime
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
date=strftime("%Y-%m-%dT%H:%M:%S")
os.chdir('/home/guillermo/TclsPy/XML_Level2/')

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8',method="xml" ,     short_empty_elements=True)
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent=" ")





for nameXml in glob.glob("*.xml"):
    new_nameXml = re.sub(r'tlmy',r'AUX',nameXml,flags=re.IGNORECASE)
    new_nameXml = re.sub('.xml','_AlarmEnabled.xml',new_nameXml, flags=re.IGNORECASE)#new_nameXml.lower().replace('.xml','_AlarmEnabled.xml')
    match = re.search(r'TSL_TM_TLMY_(.+).xml', nameXml,flags= re.IGNORECASE )
    if match:
        #Si matchea el patron, guardamos en subsistema lo que esta entre ()
        subsistema = match.group(1)
        print "Nombre:", new_nameXml
        print "Subsistema:", subsistema
    else:
        print "No matchea:", nameXml
       # raw_input()
    #<?xml version="1.0" encoding="UTF-8"?>
    TSLFunction=Element('TSLFunction')
    child = SubElement(TSLFunction, 'unit')
    child.text = '<![CDATA[AUX]]>'

    child1= SubElement(TSLFunction,'mnemonic')
    child1.text='<![CDATA'+'['+'AUX::'+'AUX.'+subsistema.replace('.xml','')+'_AlarmEnabled]]'

    child2=SubElement(TSLFunction, 'body')
    child2.text='<![CDATA[out = true;]]>'

    child3=SubElement(TSLFunction,'description')
    child3.text='<![CDATA[--]]>'

    child4=SubElement(TSLFunction,'name')
    child4.text='<![CDATA['+subsistema+'_AlarmEnabled'+']]'

    child5=SubElement(TSLFunction,'minorVersion')
    child5.text='0'

    child6=SubElement(TSLFunction,'majorVersion')
    child6.text='1'

    child7=SubElement(TSLFunction,'lastUpdate')
    child7.text=date

    child8=SubElement(TSLFunction,'creationDate')
    child8.text=date

    child9=SubElement(TSLFunction,'checked')
    child9.text='false'

    returnchild=SubElement(TSLFunction,'return')


    name=SubElement(returnchild,'name')
    name.text='<![CDATA[out]]>'

    returnType=SubElement(returnchild,'returnType')
    returnType.text='boolean'
    label=SubElement(returnchild,'label')
    label.text='<![CDATA[--]]>'

    parameters=SubElement(TSLFunction,'parameters')

    subtype=SubElement(TSLFunction,'subtype')
    subtype.text='<![CDATA[TM]]>'

    prefix=SubElement(TSLFunction,'prefix')
    prefix.text='<![CDATA[AUX]]>'

    variable=SubElement(TSLFunction,'variable')
    variable.text='<![CDATA['+subsistema +'_AlarmEnabled]]'
    print (subsistema)

    tree = ElementTree(prettify(TSLFunction))
    tree.write('../Alarm/'+new_nameXml)enter code here

最佳答案

xml.etree.ElementTree.ElementTree 类没有tostring 方法。它是 xml.etree.ElementTree 模块中的一个函数。

您已经从代码中已有的模块中导入了tostring。改变

rough_string = ElementTree.tostring(elem, 'utf-8', method="xml", short_empty_elements=True)

rough_string = tostring(elem, 'utf-8', method="xml")

它应该可以工作。

short_empty_elements 参数仅在 Python 3.4 中可用。它在 Python 2.7 中不起作用。

关于xml - 属性错误 : type object 'ElementTree' has no attribute 'tostring' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18919345/

有关xml - 属性错误 : type object 'ElementTree' has no attribute 'tostring'的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  4. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  8. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

随机推荐