python - 如何使用 lxml 和 python 漂亮地打印 xml 文件的子树?
问题描述
我有以下代码使用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"...>
获得</project>
。我将如何修改基于lxml的上述 Python 代码来做到这一点?
解决方案
我们可以使用xpath捕获嵌套元素。元素对象不提供相同的.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
推荐阅读
- java - 在 GCP 中按机器类型过滤
- node.js - `prefix ~/.npm-packages` 是否与 `prefix=${HOME}/.npm-packages` 相同
- javascript - 浏览器在用户提交表单之前擦除表单数据
- codenameone - 显示包含 PDF 链接的空白页
- javascript - 如何正确比较 javascript 中的两个图像?
- python-2.7 - with open(src, 'rb') as fsrc: IOError: [Errno 22] invalid mode ('rb') or filename:
- javascript - Node.js 数组到带有换行符的文本
- http - 授权标头
- python-3.x - 以下帮助语句中的“/”是什么意思:__init__(self, /, *args, **kwargs)?
- android - 将程序从旧的 Android Studio 版本迁移到新版本的正确方法是什么?