获取 python 中 XML 的所有相同属性值

Get all same attribute values for XML in python

我试图从“TextRegion--> Coords”标签中获取所有“points”属性值。我不断从中收到错误。注意:有名为“TextRegion”和“ImageRegion”的标签都包含“Coords”。但是,我只想要“TextRegion”中的坐标点。

请帮忙!谢谢!!

这是我的 xml 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<PcGts xmlns="http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15"
    <Metadata>
        <Creator/>
        <Created>2021-01-24T17:11:35</Created>
        <LastChange>1969-12-31T19:00:00</LastChange>
        <Comments/>
    </Metadata>
    <Page imageFilename="0004.png" imageHeight="3655" imageWidth="2493">
        <TextRegion id="r1" type="paragraph">
            <Coords points="1653,146 1651,148"/>
            <TextEquiv>
                <Unicode/>
            </TextEquiv>
        </TextRegion>
        <TextRegion id="r2" type="paragraph">
            <Coords points="2071,326 2069,328 2058,328 2055"/>
            <TextEquiv>
                <Unicode/>
            </TextEquiv>
        </TextRegion>
        <ImageRegion id="r3">
            <Coords points="443,621 443,2802 2302,2802 2302,621"/>
        </ImageRegion>
        <TextRegion id="r4" type="paragraph">
            <Coords points="2247,2825 2247,2857 2266,2857 2268,2860 2268"/>
            <TextEquiv>
                <Unicode/>
            </TextEquiv>
        </TextRegion>
        <TextRegion id="r5" type="paragraph">
            <Coords points="731,2828 731,2839 728,2841"/>
            <TextEquiv>
                <Unicode/>
            </TextEquiv>
        </TextRegion>
    </Page>
</PcGts>

这是我的代码:

from lxml import etree as ET

tree = ET.parse('0004.xml')
root = tree.getroot()
print(root.tag)

for tag in root.find_all('Page/TextRegion/Coords'):
    value = tag.get('points')
    print(value)

假设您发布的 XML 是一个 copy/paste 问题,缺少根元素打开的关闭,您的另一个主要问题是经典的 XML 解析问题,它涉及在默认情况下解析节点命名空间,包括任何以 xmlns 开头的属性,没有 冒号分隔的前缀,例如 xmlns:doc="...".

因此,您需要在 Python 中定义一个临时命名空间前缀来解析每个命名元素,您可以使用传递给 findall(不是 find_all)的字典来解析每个命名元素.

from lxml import etree as ET

tree = ET.parse('0004.xml')
nsmp = {'doc': 'http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15'}

root = tree.getroot()
print(root.tag)

# SPECIFY NAMESPACE AND PREFIX ALL NAMED ELEMENTS
for tag in root.findall('doc:Page/doc:TextRegion/doc:Coords', namespaces=nsmp):
    value = tag.get('points')
    print(value)

# 1653,146 1651,148
# 2071,326 2069,328 2058,328 2055
# 2247,2825 2247,2857 2266,2857 2268,2860 2268
# 731,2828 731,2839 728,2841

顺便说一下,lxml 是一个功能丰富的 XML 库(需要安装第 3 方),在其他强大的工具中它支持完整的 XPath 1.0。只需将 import 行更改为 from xml.etree import ElementTree as ET.

,上面的代码仍然可以与 Python 的内置 etree 一起使用

但是,比如直接解析为带有xpath的属性:

tree = ET.parse('0004.xml')

# SPECIFY NAMESPACE AND PREFIX ALL NAMED ELEMENTS
for pts in tree.xpath('//doc:Coords/@points', namespaces=nsmp):
    print(pts)

# 1653,146 1651,148
# 2071,326 2069,328 2058,328 2055
# 2247,2825 2247,2857 2266,2857 2268,2860 2268
# 731,2828 731,2839 728,2841