如何使用 lxml 获取带有子标签的所需标签?

How to get desired Tag with child Tags using lxml?

我有一个 XML 文件,例如

<?xml version="1.0" encoding="utf-8"?>
<source>
<publisher>Job App</publisher>
<publisherurl>https://jldfsfsd.jlfdfs.com/Jobs/</publisherurl>
<lastBuildDate>10-19-2015 00:00:00</lastBuildDate>
<job>
    <title><![CDATA[Barista/Sandwich Prep]]></title>
    <date><![CDATA[10-19-2015]]></date>
    <referencenumber><![CDATA[83]]></referencenumber>
    <url><![CDATA[https://test/Jobs/Job.aspx?JobPostingId=83&SourceId=3]]></url>
    <company><![CDATA[Another Cafe]]></company>
    <city><![CDATA[San Francisco]]></city>
    <state><![CDATA[California]]></state>
    <country><![CDATA[United States of America]]></country>
    <postalcode><![CDATA[94123]]></postalcode>
    <description><![CDATA[  TESTTESTTESTTESTTESTTESTTESTTEST <br> STEdsasjflsdf<p> dfjhdjlas </p>]]></description> 
</job>
<job>
    <title><![CDATA[MV Drivers]]></title>
    <date><![CDATA[01-01-1900]]></date>
    <referencenumber><![CDATA[147]]></referencenumber>
    <url><![CDATA[https://sdf.dsfs.com/Jobs/Job.aspx?JobPostingId=147&SourceId=3]]></url>
    <company><![CDATA[Papa Johns Pizza]]></company>
    <city><![CDATA[Mountain View]]></city>
    <state><![CDATA[California]]></state>
    <country><![CDATA[United States of America]]></country>
    <book><![CDATA[BOOKTEST]]></book>
    <postalcode><![CDATA[94404]]></postalcode>
    <description><![CDATA[Fun sfsf job while makingfsfup to /hour!]]></description>    
</job>


在 lxml 解析器中,如何仅获取第二个作业标记及其子节点意味着我只想获取以下数据作为输出。请注意,这不是固定格式,它取决于 XML 文件结构。

      <job>
        <title><![CDATA[MV Drivers]]></title>
        <date><![CDATA[01-01-1900]]></date>
        <referencenumber><![CDATA[147]]></referencenumber>
        <url><![CDATA[https://sdf.dsfs.com/Jobs/Job.aspx?JobPostingId=147&SourceId=3]]></url>
        <company><![CDATA[Papa Johns Pizza]]></company>
        <city><![CDATA[Mountain View]]></city>
        <state><![CDATA[California]]></state>
        <country><![CDATA[United States of America]]></country>
        <postalcode><![CDATA[94404]]></postalcode>
        <description><![CDATA[Fun sfsf job while makingfsfup to /hour!]]></description>    
    </job>

您可以遍历文档中的元素,并提取第二个 'job' 元素。使用 Element class.

iter 方法非常容易
from lxml import etree

tree = etree.parse('data.xml') #or whatever is your file name
root = tree.getroot()
job_elements = list(root.iter('job'))

job_elements 是一个列表,其中所有标记为 'job' 的元素按文档中出现的顺序排列。取第二个(索引 1)。
要打印它(及其所有子元素),您可以使用 etree.tostring 函数。这将 return 一个二进制字符串,因此要在控制台上很好地显示它,您可能需要将其解码为 ascii。

output = etree.tostring(job_elements[1], pretty_print=True)
print(output.decode('ascii'))

更多详情

etree.parse() return 是一个 ElementTree 对象。使用 getroot() 你会得到一个从 ElementTree 的根开始的 Element 对象(Element 有更多方法)。实际上不需要这一行,因为您需要 iter 方法并且 ElementTree 也有一个 iter 方法,我添加只是出于习惯。但是,如果您要对树进行一些额外的操作,使用 Element 而不是 ElementTree.

可能会很有用

job_elements = list(root.iter('job'))关键是iter method。它 return 是按文档顺序沿着子树中的元素的迭代器(有关详细信息,请参阅链接文档)。