【问题标题】:python print last element value in XMLpython在XML中打印最后一个元素值
【发布时间】:2018-08-22 21:25:28
【问题描述】:

使用 ElementTree,我在这里浏览了大量帖子,但找不到任何特定于我的 xml 的帖子。我想在下面的示例 xml 中返回最后一个时间戳

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Entities TotalResults="125">
    <Entity Type="defect">
        <Fields>
            <Field Name="id">
                <Value>520342</Value>
            </Field>
            <Field Name="priority">
                <Value></Value>
            </Field>
            <Field Name="user-08">
                <Value>8/20/2018 9:52:01 PM</Value>
            </Field>
        </Fields>
        <RelatedEntities/>
    </Entity>
    <Entity Type="defect">
        <Fields>
            <Field Name="id">
                <Value>520574</Value>
            </Field>
            <Field Name="priority">
                <Value></Value>
            </Field>
            <Field Name="user-08">
                <Value>8/20/2018 10:52:01 PM<</Value>
            </Field>
        </Fields>
        <RelatedEntities/>
    </Entity>
</Entities>

【问题讨论】:

  • 您的 XML 格式不正确 -- 第二个时间戳中有一个额外的 &lt;

标签: python xml parsing elementtree findall


【解决方案1】:

使用上面格式正确的 XML 版本,这将专门找到最后一个时间戳作为字符串。如果没有更多信息,我无法确保这完全可以扩展。

t = root[-1].find(".//*[@Name='user-08']/Value").text
print(t)
#=> 8/20/2018 10:52:01 PM

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2022-08-17
    相关资源
    最近更新 更多