English 中文(简体)
Python 动态生成 XML
原标题:Generating XML dynamically in Python

各位朋友,我正在使用 Python 库生成XML 数据,如下:

def multiwan_info_save(request):
    data = {}
    init = "init"
    try:
       form = Addmultiwanform(request.POST)
    except:
        pass
    if form.is_valid():
        from_sv = form.save(commit=False)
        obj_get = False
        try:
            obj_get = MultiWAN.objects.get(isp_name=from_sv.isp_name)
        except:
            obj_get = False
            nameservr  = request.POST.getlist( nameserver_mw ) 
            for nm in nameservr:
                nameserver1, is_new = NameServer.objects.get_or_create(name=nm)
                from_sv.nameserver = nameserver1
                from_sv.save()
        #    main(init)    
        top = Element( ispinfo )
       # comment = Comment( Generated for PyMOTW )
        #top.append(comment)
        all_connection = MultiWAN.objects.all()
        for conn in all_connection:
            child = SubElement(top,  connection number = +str(conn.id)+ name= +conn.isp_name+ desc= +conn.description )
            subchild_ip = SubElement(child, ip_address )
            subchild_subnt = SubElement(child, subnet )
            subchild_gtwy = SubElement(child, gateway )
            subchild_nm1 = SubElement(child, probe_server1 )
            subchild_nm2 = SubElement(child, probe_server2 )
            subchild_interface = SubElement(child, interface )
            subchild_weight = SubElement(child, weight )
            subchild_ip.text = str(conn.ip_address)
            subchild_subnt.text = str(conn.subnet)
            subchild_gtwy.text = str(conn.gateway)
            subchild_nm1.text = str(conn.nameserver.name)
           # subchild_nm2.text = conn.
            subchild_weight.text = str(conn.weight)
            subchild_interface.text = str(conn.interface)
        print "trying to print _____________________________"
        print tostring(top)   
        print "let seeeeeeeeeeeeeeeeee +++++++++++++++++++++++++"

但我得到的输出 喜欢跟随

<ispinfo><connection number =5name=Airtelllldesc=Largets TRelecome ><ip_address>192.168.1.23</ip_address><subnet>192.168.1.23</subnet><gateway>192.168.1.23</gateway><probe_server1>192.168.99.1</probe_server1><probe_server2 /><interface>eth0</interface><weight>160</weight></connection number =5name=Airtelllldesc=Largets TRelecome ><connection number =6name=Uninordesc=Uninor><ip_address>192.166.55.23</ip_address><subnet>192.166.55.23</subnet><gateway>192.168.1.23</gateway><probe_server1>192.168.99.1</probe_server1><probe_server2 /><interface>eth0</interface><weight>160</weight></connection number =6name=Uninordesc=Uninor><connection number =7name=Airteldesc=Largets TRelecome ><ip_address>192.168.1.23</ip_address><subnet>192.168.1.23</subnet><gateway>192.168.1.23</gateway><probe_server1>192.168.99.1</probe_server1><probe_server2 /><interface>eth0</interface><weight>160</weight></connection number =7name=Airteldesc=Largets TRelecome ></ispinfo>

我只想知道 我怎么能用XML格式写这个XML?

提前感谢

最佳回答

< 强 > Upped 包含 XML 树 创建和打印的模拟

The Basic Issue

您的代码正在生成无效的连接标记 :

<connection number =5name=Airtelllldesc=Largets TRelecome ></connection number =5name=Airteldesc=Largets TRelecome >

当他们长成这样的时候(我将省略介于其中的子元素),你的代码正正确生成这些子元素:

<connection number="5" name="Airtellll" desc="Largets TRelecome" ></connection>

如果您有有效的 XML, 这个代码会打印得整洁:

from lxml import etree
xml =    <ispinfo><connection number="5" name="Airtellll" desc="Largets TRelecome" ><ip_address>192.168.1.23</ip_address><subnet>192.168.1.23</subnet><gateway>192.168.1.23</gateway><probe_server1>192.168.99.1</probe_server1><probe_server2 /><interface>eth0</interface><weight>160</weight></connection></ispinfo>   
xml = etree.XML(xml)
print etree.tostring(xml, pretty_print = True)

Generating Valid XML

小型模拟如下:

from lxml import etree

# Some dummy text
conn_id = 5
conn_name = "Airtelll"
conn_desc = "Largets TRelecome"
ip = "192.168.1.23"

# Building the XML tree
# Note how attributes and text are added, using the Element methods
# and not by concatenating strings as in your question
root = etree.Element("ispinfo")
child = etree.SubElement(root,  connection ,
                 number = str(conn_id),
                 name = conn_name,
                 desc = conn_desc)
subchild_ip = etree.SubElement(child,  ip_address )
subchild_ip.text = ip

# and pretty-printing it
print etree.tostring(root, pretty_print=True)

这将产生:

<ispinfo>
  <connection desc="Largets TRelecome" number="5" name="Airtelll">
    <ip_address>192.168.1.23</ip_address>
  </connection>
</ispinfo>
问题回答

单行为proper ,意思是XML 分析器会理解它。

对于 sys.stdout 的漂亮打印,请使用 dump 方法 Eplement

对于流体的漂亮打印,请使用 write 方法 EplementTree





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签