[英]How to use lxml and python to pretty print a subtree of an xml file?
我有以下代码使用python和lxml来打印文件example.xml :
python -c '
from lxml import etree;
from sys import stdout, stdin;
parser=etree.XMLParser(remove_blank_text=True, strip_cdata=False);
tree=etree.parse(stdin, parser)
tree.write(stdout, pretty_print = True)' < example.xml
我正在使用lxml,因为保持原始文件的保真度非常重要,包括保留CDATA惯用语。 这是我正在使用它的文件example.xml :
<projects><project name="helloworld" threads="1" pubsub="auto" heartbeat-interval="1">
<description><![CDATA[This is a sample project]]></description> <metadata> <meta id="studioUploadedBy">anonymous</meta>
<meta id="studioUploaded">1550863090439</meta> <meta id="studioModifiedBy">anonymous</meta>
<meta id="studioModified">1550863175384</meta> <meta id="studioTags">helloworld</meta>
<meta id="studioVersionNotes">This is just a sample project</meta> <meta id="layout">{"cq1":{"Source1":{"x":50,"y":-290}}}</meta>
</metadata> <contqueries> <contquery name="cq1"> <windows> <window-source pubsub="true" name="Source1">
<schema> <fields> <field name="name" type="string" key="true"/> </fields>
</schema> </window-source> </windows> </contquery> </contqueries> </project></projects>
它生成以下输出:
<projects>
<project name="helloworld" threads="1" pubsub="auto" heartbeat-interval="1">
<description><![CDATA[This is a sample project]]></description>
<metadata>
<meta id="studioUploadedBy">anonymous</meta>
<meta id="studioUploaded">1550863090439</meta>
<meta id="studioModifiedBy">anonymous</meta>
<meta id="studioModified">1550863175384</meta>
<meta id="studioTags">helloworld</meta>
<meta id="studioVersionNotes">This is just a sample project</meta>
<meta id="layout">{"cq1":{"Source1":{"x":50,"y":-290}}}</meta>
</metadata>
<contqueries>
<contquery name="cq1">
<windows>
<window-source pubsub="true" name="Source1">
<schema>
<fields>
<field name="name" type="string" key="true"/>
</fields>
</schema>
</window-source>
</windows>
</contquery>
</contqueries>
</project>
</projects>
这几乎是我想要的,除了我想得到一个子树。 我希望能够得到子树<project name="helloworld"...>
thru </project>
。 我如何修改基于lxml的上述Python代码来做到这一点?
我们可以使用xpath捕获嵌套的Element。 元素对象不提供相同的.write()
功能,因此我们需要一个不同的输出机制。
怎么样...
python -c '
from lxml import etree;
from sys import stdout, stdin;
parser=etree.XMLParser(remove_blank_text=True, strip_cdata=False);
tree=etree.parse(stdin, parser)
# assuming there will be exactly 1 project
project=tree.xpath("project")[0]
print etree.tostring(project, pretty_print = True)' < example.xml
您可以使用tree.find来获取需要提取的xml元素。 他们将其转换为元素树。 然后,您可以在这种情况下对结果elementtree(et)发出write语句。
python -c '
from lxml import etree;
from sys import stdout, stdin;
parser=etree.XMLParser(remove_blank_text=True,strip_cdata=False);
tree=etree.parse(stdin, parser)
e = tree.find("project")
et = etree.ElementTree(e)
et.write(stdout, pretty_print = True)'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.