通过对 minidom 内容处理程序进行猴子修补,我能够记录每个节点的行号和列号(作为 'parse_position' 属性)。这有点脏,但我看不到任何“官方认可”的做法:) 这是我的测试脚本:
from xml.dom import minidom
import xml.sax
doc = """\
<File>
<name>Name</name>
<pos>./</pos>
</File>
"""
def set_content_handler(dom_handler):
def startElementNS(name, tagName, attrs):
orig_start_cb(name, tagName, attrs)
cur_elem = dom_handler.elementStack[-1]
cur_elem.parse_position = (
parser._parser.CurrentLineNumber,
parser._parser.CurrentColumnNumber
)
orig_start_cb = dom_handler.startElementNS
dom_handler.startElementNS = startElementNS
orig_set_content_handler(dom_handler)
parser = xml.sax.make_parser()
orig_set_content_handler = parser.setContentHandler
parser.setContentHandler = set_content_handler
dom = minidom.parseString(doc, parser)
pos = dom.firstChild.parse_position
print("Parent: '{0}' at {1}:{2}".format(
dom.firstChild.localName, pos[0], pos[1]))
for child in dom.firstChild.childNodes:
if child.localName is None:
continue
pos = child.parse_position
print "Child: '{0}' at {1}:{2}".format(child.localName, pos[0], pos[1])
Run Code Online (Sandbox Code Playgroud)
它输出以下内容:
Parent: 'File' at 1:0
Child: 'name' at 2:2
Child: 'pos' at 3:2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2814 次 |
| 最近记录: |