0

请查看下面的代码,我正在使用它来使用 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>

平均数字属性应该用单引号括起来。任何想法....我怎样才能做到这一点

4

1 回答 1

0

There is no flag in lxml to do this, so you have to resort to manual manipulation.

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

However, why do you want to do this? As there is no difference other than cosmetics.

于 2012-05-28T12:09:20.630 回答