"""
python sax解析xml
无法进行解析
"""
import xml.sax
class SchoolHandler(xml.sax.ContentHandler):
def init(self):
self.CurrentData = ""
self.name = ""
self.format = ""
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "school":
print("**school")
level = attributes['level']
print("Level: ", level)
def endElement(self, tag):
if self.CurrentData == "name":
print("name:", self.name)
elif self.CurrentData == "year":
print("year:", self.year)
self.CurrentData = ""
def characters(self, content):
if self.CurrentData == "name":
self.name = content
elif self.CurrentData == "year":
self.year = content
if name == "main":
# 创建一个XMLReader
parser = xml.sax.make_parser(['xml.sax.drivers2.drv_lxml'])
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namepsaces, 0)
# 重写ContextHandler()
Handler = SchoolHandler()
parser.setContentHandler(Handler)
parser.parse("school_sax.xml")
出现的问题:
C:\Users\HP\AppData\Local\Programs\Python\Python312\pytho.exe\Scripts\python.exe D:\pythonProject1\SAX_DOM.py
Traceback (most recent call last):
File "D:\pythonProject1\SAX_DOM.py", line 15, in <module>
parser = xml.sax.make_parser()
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\HP\AppData\Local\Programs\Python\Python312\Lib\xml\sax_init_.py", line 88, in make_parser
raise SAXReaderNotAvailable("No parsers found", None)
xml.sax._exceptions.SAXReaderNotAvailable: No parsers found
进程已结束,退出代码1
问题出现在你尝试创建XML解析器时,它无法找到可用的解析器。这通常是因为未正确安装XML解析器库或由于某些配置问题导致的。
在你的代码中,你尝试使用lxml解析器,但在你的导入语句中有一个小错误。你应该导入lxml库,而不是使用xml.sax.drivers2.drv_lxml,因此请更正以下代码:
python
import xml.sax
from xml.sax import handler
然后,尝试创建解析器时,不需要指定解析器的参数,因为通常情况下,Python会自动选择一个可用的解析器。请修改以下代码:
python
parser = xml.sax.make_parser()
完整的代码如下:
python
Copy code
import xml.sax
class SchoolHandler(xml.sax.ContentHandler):
def init(self):
self.CurrentData = ""
self.name = ""
self.year = ""
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "school":
print("**school")
level = attributes['level']
print("Level: ", level)
def endElement(self, tag):
if self.CurrentData == "name":
print("name:", self.name)
elif self.CurrentData == "year":
print("year:", self.year)
self.CurrentData = ""
def characters(self, content):
if self.CurrentData == "name":
self.name = content
elif self.CurrentData == "year":
self.year = content
if name == "__main":
parser = xml.sax.make_parser()
Handler = SchoolHandler()
parser.setContentHandler(Handler)
parser.parse("school_sax.xml")
确保你已正确安装lxml库,如果没有安装,可以使用以下命令安装:
bash
pip install lxml
然后尝试重新运行你的代码,它应该能够成功解析XML文件。
仍然没有解决
试试把这个parser = xml.sax.make_parser(['xml.sax.drivers2.drv_lxml']),改成这个parser = xml.sax.make_parser()
结帖
– 溯流 11个月前