如何使用lxml和python漂亮地打印xml文件的子树?

时间:2019-03-27 19:54:19

标签: python lxml

我有以下代码,使用 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代码来做到这一点?

2 个答案:

答案 0 :(得分:2)

我们可以使用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

答案 1 :(得分:2)

您可以使用tree.find获取需要提取的xml元素。他们将其转换为元素树。然后,在这种情况下,您可以在结果的元素树(et)上发出写语句。

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)'