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

时间:2012-12-06 11:20:14

标签: python

我有一些像这样的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?

由于各种原因我无法使用任何第三方软件包。

e.g。上面的xml是不正确的,因为它有'&amp;'在里面。请注意,DOCTYPE定义句子指的是DTD。

2 个答案:

答案 0 :(得分:28)

尝试使用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

答案 1 :(得分:6)

您可以使用python的xml.dom.minidom XML解析器(位于标准库中,但不如lxml等替代功能强大。)

只是做:

import xml.dom.minidom
xml.dom.minidom.parseString('<My><XML><String/><XML/><My/>')

如果XML无效,您将获得xml.parsers.expat.ExpatError