gpt4 book ai didi

python - 如何在没有第三方库的情况下使用 python 验证 xml?

转载 作者:太空狗 更新时间:2023-10-29 17:01:30 25 4
gpt4 key购买 nike

我有一些像这样的 xml 片段:

<!DOCTYPE mensaje SYSTEM "record.dtd">
<record>
<player_birthday>1979-09-23</player_birthday>
<player_name>Orene Ai'i</player_name>
<player_team>Blues</player_team>
<player_id>453</player_id>
<player_height>170</player_height>
<player_position>F&W</player_position> <---- a '&' here.
<player_weight>75</player_weight>
</record>

有什么方法可以验证 xml 片段的格式是否正确?有什么方法可以根据 DTD 或 XML 方案验证 xml?

由于各种原因我不能使用任何第三方包。

例如上面的 xml 不正确,因为其中有一个“&”。请注意,DOCTYPE 定义语句指的是 DTD。

最佳答案

只需尝试使用 ElementTree (xml.etree.ElementTree.fromstring) 解析它 - 如果 XML 格式不正确,它将引发错误。

>>> a = """<record>
... <player_birthday>1979-09-23</player_birthday>
... <player_name>Orene Ai'i</player_name>
... <player_team>Blues</player_team>
... <player_id>453</player_id>
... <player_height>170</player_height>
... <player_position>F&W</player_position> <---- a '&' here.
... <player_weight>75</player_weight>
... </record>"""
>>>
>>> from xml.etree import ElementTree as ET
>>> x = ET.fromstring(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1282, in XML
parser.feed(text)
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1624, in feed
self._raiseerror(v)
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1488, in _raiseerror
raise err
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 7, column 24

关于python - 如何在没有第三方库的情况下使用 python 验证 xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13742538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com