【问题标题】:Find all attributes which are number using lxml使用 lxml 查找所有数字属性
【发布时间】:2020-10-26 21:36:48
【问题描述】:

我正在使用 lxml 和 python 3.7 来解析 XML 文件。

我想遍历我的 XML 中包含数字的所有属性。此数字可以是实数或整数(例如 1、5.2234)。

有没有办法使用 xpath 遍历所有这些属性?或其他任何使用 lxml 的东西?

简短示例:

<scenario name="ChangeLane_2" type="ChangeLane" town="Town01">
    <ego_vehicle x="107" y="133.5" z="0.5" yaw="0" model="vehicle.lincoln.mkz2017" />
</scenario>

预期的分辨率将是元素属性:xyzyaw

【问题讨论】:

  • 您可以编辑您的问题并添加示例 xml 以及该示例的预期输出吗?

标签: python-3.x xml xpath lxml


【解决方案1】:

在 lxml 中迭代由 XPath 选择的属性(如 //@someattribute)的问题是它返回一个 _ElementUnicodeResult;不是具有名称或父级等属性的对象。

例如,如果你这样做:

print(tree.xpath("//@*[not(string(number(.))='NaN')]"))

你得到:

['107', '133.5', '0.5', '0']

这只是值。

我认为您必须做的是在选择父元素后迭代属性,然后尝试查看它是否可以转换为数字(浮点数或其他)。

示例...

from lxml import etree

xml = """<scenario name="ChangeLane_2" type="ChangeLane" town="Town01">
    <ego_vehicle x="107" y="133.5" z="0.5" yaw="0" model="vehicle.lincoln.mkz2017" />
</scenario>"""

tree = etree.fromstring(xml)

for elem in tree.xpath("//*[@*[not(string(number(.))='NaN')]]"):
    attrs = []
    for attr in elem.attrib:
        try:
            float(elem.get(attr))
            attrs.append(attr)
        except ValueError:
            pass
    print(attrs)

打印输出:

['x', 'y', 'z', 'yaw']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 2012-12-23
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多