本文摘自php中文网,作者黄舟,侵删。
这篇文章主要为大家详细介绍了python利用lxml读写xml格式的文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下之前在转换数据集格式的时候需要将json转换到xml文件,用lxml包进行操作非常方便。
1. 写xml文件
a) 用etree和objectify
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from lxml import etree, objectify
E = objectify.ElementMaker(annotate = False )
anno_tree = E.annotation(
E.folder( 'VOC2014_instance' ),
E.filename( "test.jpg" ),
E.source(
E.database( 'COCO' ),
E.annotation( 'COCO' ),
E.image( 'COCO' ),
E.url( "http://test.jpg" )
),
E.size(
E.width( 800 ),
E.height( 600 ),
E.depth( 3 )
),
E.segmented( 0 ),
)
etree.ElementTree(anno_tree).write( "text.xml" , pretty_print = True )
|
输出的test.xml文件内容如下:
"
如果需要在anno_tree的基础上加其他标签的话用append即可:
1 2 3 4 5 6 7 8 9 10 11 12 | E2 = objectify.ElementMaker(annotate = False )
anno_tree2 = E2. object (
E.name( "person" ),
E.bndbox(
E.xmin( 100 ),
E.ymin( 200 ),
E.xmax( 300 ),
E.ymax( 400 )
),
E.difficult( 0 )
)
anno_tree.append(anno_tree2)
|
上面的输出就变成了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <annotation>
<folder>VOC2014_instance / person< / folder>
<filename>test.jpg< / filename>
<source>
<database>COCO< / database>
<annotation>COCO< / annotation>
<image>COCO< / image>
<url>http: / / test.jpg< / url>
< / source>
<size>
<width> 800 < / width>
<height> 600 < / height>
<depth> 3 < / depth>
< / size>
<segmented> 0 < / segmented>
< object >
<name>person< / name>
<bndbox>
<xmin> 100 < / xmin>
<ymin> 200 < / ymin>
<xmax> 300 < / xmax>
<ymax> 400 < / ymax>
< / bndbox>
<difficult> 0 < / difficult>
< / object >
< / annotation>
|
b) 用etree和SubElement
阅读剩余部分
相关阅读 >>
Python在excel中的应用是什么
Python连接mysql的方式总结
比较Python序列化模块pickle和json不同
Python字典一个键只能有一个值吗
爬虫能获取什么样的数据和具体的解析方式
用matplotlib如何绘制条形图、直方图和散点图
Python利用requests库写爬虫的实例详解
Python基本语句有哪些
Python中pandas和xlsxwriter读写xlsx文件的方法介绍(附代码)
Python--aes加密与解密方法指导
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python如何使用lxml来读写xml格式文件的实例分享