如何使用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代码来做到这一点?

解决方法:

您可以使用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)'
上一篇:python使用lxml和xpath解析html表上的特定数据


下一篇:python-从一个文件中解析特定的XML属性,并将其追加到另一个文件中,前提是第二个文件中存在另一个属性