使用python生成Xml

时间:2012-05-28 11:26:25

标签: python xml xml-parsing

请看下面的代码,我使用它来生成使用python的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>

但我希望它像:

<ispinfo>
  <connection desc="Largets TRelecome" number='1' name="Airtelll">
    <ip_address>192.168.1.23</ip_address>
  </connection>
</ispinfo>

平均数字属性应该是单引号。任何想法....我怎样才能实现这个

1 个答案:

答案 0 :(得分:0)

lxml中没有标志来执行此操作,因此您必须采用手动操作。

import re
re.sub(r'number="([0-9]+)"',r"number='\1'", etree.tostring(root, pretty_print=True))

但是,你为什么要这样做?除了化妆品之外没有区别。

相关问题