我想从文件“new.xml”中删除xml标记,并根据print语句放置数据。
我尝试过:
from lxml import etree
tree = etree.parse("C:\\Users\\name\\Desktop\\new.xml")
root = tree.getroot()
for text in root.iter():
print text.text
XML代码是:
<connection>
<rhel>
<runscript>y</runscript>
<username>useranme</username>
<password>passw</password>
<store>None</store>
<port>2</port>
<host>192.168.73.56</host>
<logdirectory>logs</logdirectory>
</rhel>
</connection>
我得到以下输出:
yes
username
passw
None
2
192.168.73.56
logs
但我想把它打印成:
is it a new connection: yes
username: username
password: passw
value: none
connections: 2
host: 192.168.73.56
log dir : logs
答案 0 :(得分:1)
您需要根据XML文件的结构进行解析。为此,您可以循环遍历子项,并查看每个项的标记名称和文本。
from lxml import etree
tree = etree.parse("test.xml")
root = tree.getroot()
connections = []
for node in root.findall('rhel'): # for all the 'rhel' nodes, children of the root 'connections' node
connections.append({info.tag: info.text for info in node}) # Construct a dictionary with the (tag, text) as (key, value) pair.
print connections
for conn in connections:
print '='*20
print """is it a new connection: {runscript}
username: {username}
password: {password}
value: {store}
connections: {port}
host: {host}
log dir : {logdirectory}""".format(**conn)
你这样做的方式,你可以尝试:repr(root)
。你会得到正在印刷的东西。但不建议这样做,原因有很多:
希望它有所帮助。
<强>更新强>:
对于Python&lt; 2.7,您可以使用connections.append(dict((info.tag, info.text) for info in node))
而不是其他行。我猜之前不支持这种表示法。
或者,最终,你可以这样做:
c = {}
for info in node:
c[info.tag] = info.text
connections.append(c)
此外,如果在Python 2.6上,我猜这种格式也可能不起作用。将其替换为旧的字符串格式:
print """is it a new connection: %(runscript)s
username: %(username)s
password: %(password)s
value: %(store)s
connections: %(port)s
host: %(host)s
log dir : %(logdirectory)s""" % conn