python报告XML节点的行/列

Jer*_*ade 6 python xml dom sax

我目前正在使用xml.dom.minidom来解析python中的一些XML.在解析之后,我正在对内容进行一些报告,并且想要报告源XML文档中标记开始的行(和列),但我不知道这是怎么回事.

如果可能的话,我想坚持使用xml.dom/xml.dom.minidom,但是如果我需要使用SAX解析器来获取原始信息,我可以这样做 - 理想的情况是使用SAX来跟踪节点位置,但最终仍然有一个DOM用于我的后期处理.

有关如何做到这一点的任何建议?希望我只是忽略了文档中的内容,这非常容易.

akn*_*ds1 5

通过对 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)