【问题标题】:How to read this XML file in python如何在 python 中读取这个 XML 文件
【发布时间】:2020-12-05 11:26:00
【问题描述】:

我正在尝试为一个项目读取一些 xml 数据,但它不起作用...我有这个代码(使用的 xml 文件如下所示):

import time
from xml.etree.ElementTree import fromstring, ElementTree
import xml.etree.ElementTree as ET
ET.register_namespace('', "http://www.w3.org/2001/XMLSchema-instance")
ET.register_namespace('', "http://bison.connekt.nl/tmi8/kv6/msg")

while True:
    print("--------------------------------------------")
    tree = ET.parse("RET.xml")
    root = tree.getroot()
    print(root)
    for debug in root.findall(".//"): 
        print(debug.text)
    for line in root.findall('.Version'):
    print(line.text)
    print("--------------------------------------------")
    time.sleep(5)

它成功地找到了所有元素的内容,但是当我搜索像“版本”这样的特定元素时,它不会返回任何内容。这是当前的输出:


<Element '{http://bison.connekt.nl/tmi8/kv6/msg}VV_TM_PUSH' at 0x03D775A0>

RET

BISON 8.1.1.0
KV6posinfo
2020-12-04T21:22:56.1275145+01:00
ttt

RET
M007

2020-12-04

200180

0

HA8215

0

2020-12-04T21:22:56.1119143+01:00

SERVER

0
-920

--------------------------------------------

这是使用的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<VV_TM_PUSH xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://bison.connekt.nl/tmi8/kv6/msg">
<SubscriberID>
RET</SubscriberID><Version>
BISON 8.1.1.0</Version>
<DossierName>KV6posinfo</DossierName>
<Timestamp>2020-12-04T21:22:56.1275145+01:00</Timestamp>
<KV6posinfo>ttt
<ONSTOP>
<dataownercode>RET</dataownercode>
<lineplanningnumber>M007</lineplanningnumber>
<operatingday>2020-12-04</operatingday>
<journeynumber>200180</journeynumber>
<reinforcementnumber>0</reinforcementnumber>
<userstopcode>HA8215</userstopcode>
<passagesequencenumber>0</passagesequencenumber>
<timestamp>2020-12-04T21:22:56.1119143+01:00</timestamp>
<source>SERVER</source>
<vehiclenumber>0</vehiclenumber>
<punctuality>-920</punctuality>
</ONSTOP>
</KV6posinfo>
</VV_TM_PUSH>

出于测试目的,我在标签中添加了“ttt”。

谁能帮忙?

【问题讨论】:

标签: python xml-parsing elementtree


【解决方案1】:

我发现您的代码中有 2 个缺陷:

  1. for line in root.findall('.Version'): 行中有不必要的点。 注意 Version 是根元素的直接后代,所以它 只放标签名就够了(其实不只放,后面详述)。
  2. print(line.text) 行没有缩进,所以实际上你应该有 收到编译错误。

现在如何正确使用 namespaced XML:

请注意,您的输入文件包含默认命名空间 (http://bison.connekt.nl/tmi8/kv6/msg)

那么如果你想引用这个命名空间中的任何元素,你必须:

  • 定义一个命名空间字典(键 - 前缀,值 - URI),在你 只有一对“prefix:URI”,
  • 在标签名称前加上命名空间前缀和冒号,
  • 将命名空间字典作为第二个参数传递给例如找到

因此,在您的情况下,将相应的代码片段替换为:

ns = {'bis': 'http://bison.connekt.nl/tmi8/kv6/msg'}
for line in root.findall('bis:Version', ns):
    print(f'Version: {line.text}')

我添加了 Version: 以表明已打印的内容。

考虑也打印 line.text.strip(),因为你的标签有一个前导 换行

【讨论】:

    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多