Home  >  Q&A  >  body text

Python:使用sax解析包含多个子节点的xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <system value="mysql">
        <title>标题</title>
        <search>
            <s1>搜索1</s1>
            <s2>搜索2</s2>
        </search>
        <test>
            <subTest1>111</subTest1>            
            <subTest2>222</subTest2>            
            <subTest3>333</subTest3>
        </test>
    </system>
</root>

使用sax如何处理包含有多个子节点的xml呢?
比如:我想将每个system节点保存到一个dictionary中,然后通过下标来访问

dict['mysql']['search']['s1']=搜索1
dict['mysql']['test']['subTest1']=111

目前想到2中方法:
1.重写 startElement,endElement,characters方法,在其中进行判断
2.递归
第一种方法,已实现,不是很满意(需要继承ContentHandler,并重写几个函数,在函数中进行多种判断)
第二种方法,还没去实现

PHPzPHPz2743 days ago976

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:28:07

    There is something called xmltodict... Your needs can be met in one step. There is no need to use sax to parse. Sax is more suitable for converting xml into instance objects

    reply
    0
  • Cancelreply