使用元素树读取XML文件
我有一个xml文件。
它的内容大概是这样的:
<root>
<Group>
<ChapterNo>1</ChapterNo>
<ChapterName>A</ChapterName>
<Line>1</Line>
<Content>zfsdfsdf</Content>
<Synonyms>fdgd</Synonyms>
<Translation>assdfsdfsdf</Translation>
</Group>
<Group>
<ChapterNo>1</ChapterNo>
<ChapterName>A</ChapterName>
<Line>2</Line>
<Content>ertreter</Content>
<Synonyms>retreter</Synonyms>
<Translation>erterte</Translation>
</Group>
<Group>
<ChapterNo>2</ChapterNo>
<ChapterName>B</ChapterName>
<Line>1</Line>
<Content>sadsafs</Content>
<Synonyms>sdfsdfsd</Synonyms>
<Translation>sdfsdfsd</Translation>
</Group>
<Group>
<ChapterNo>2</ChapterNo>
<ChapterName>B</ChapterName>
<Line>2</Line>
<Content>retete</Content>
<Synonyms>retertret</Synonyms>
<Translation>retertert</Translation>
</Group>
</root>
我尝试了这种方法……
root = ElementTree.parse('data.xml').getroot()
ChapterNo = root.find('ChapterNo').text
ChapterName = root.find('ChapterName').text
GitaLine = root.find('Line').text
Content = root.find('Content').text
Synonyms = root.find('Synonyms').text
Translation = root.find('Translation').text
但是它显示了一个错误
ChapterNo=root.find('ChapterNo').text
AttributeError: 'NoneType' object has no attribute 'text'`
现在我想用元素树(element tree)把所有的章节编号(ChapterNo)、章节名称(ChapterName)等信息分别提取出来,并想把这些数据插入到数据库里……有没有人能帮我?
祝好,
Nimmy
3 个回答
0
这里有一个小例子,使用sqlalchemy
来定义一个对象,这个对象会提取数据并把它存储到sqlite数据库中。
from sqlalchemy import create_engine, Unicode, Integer, Column, UnicodeText
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///chapters.sqlite', echo=True)
Base = declarative_base(bind=engine)
class ChapterLine(Base):
__tablename__ = 'chapterlines'
chapter_no = Column(Integer, primary_key=True)
chapter_name = Column(Unicode(200))
line = Column(Integer, primary_key=True)
content = Column(UnicodeText)
synonyms = Column(UnicodeText)
translation = Column(UnicodeText)
@classmethod
def from_xmlgroup(cls, element):
l = cls()
l.chapter_no = int(element.find('ChapterNo').text)
l.chapter_name = element.find('ChapterName').text
l.line = int(element.find('Line').text)
l.content = element.find('Content').text
l.synonyms = element.find('Synonyms').text
l.translation = element.find('Translation').text
return l
Base.metadata.create_all() # creates the table
下面是如何使用它的:
from xml.etree import ElementTree as etree
session = create_session(bind=engine, autocommit=False)
doc = etree.parse('myfile.xml').getroot()
for group in doc.findall('Group'):
l = ChapterLine.from_xmlgroup(group)
session.add(l)
session.commit()
我已经在你的xml数据上测试过这段代码,运行得很好,所有数据都成功插入到数据库里。
1
ChapterNo
不是 root
的直接子元素,所以 root.find('ChapterNo')
这个方法无法找到它。你需要使用 xpath 语法来查找数据。
另外,ChapterNo
、ChapterName
等元素出现了多次,所以你应该使用 findall
方法,并遍历结果来获取每一个的文本内容。
chapter_nos = [e.text for e in root.findall('.//ChapterNo')]
等等。
2
要解析你简单的两层数据结构,并为每个组组装一个字典,你只需要这样做:
>>> # what you did to get `root`
>>> from pprint import pprint as pp
>>> for group in root:
... d = {}
... for elem in group:
... d[elem.tag] = elem.text
... pp(d) # or whack it ito a database
...
{'ChapterName': 'A',
'ChapterNo': '1',
'Content': 'zfsdfsdf',
'Line': '1',
'Synonyms': 'fdgd',
'Translation': 'assdfsdfsdf'}
{'ChapterName': 'A',
'ChapterNo': '1',
'Content': 'ertreter',
'Line': '2',
'Synonyms': 'retreter',
'Translation': 'erterte'}
{'ChapterName': 'B',
'ChapterNo': '2',
'Content': 'sadsafs',
'Line': '1',
'Synonyms': 'sdfsdfsd',
'Translation': 'sdfsdfsd'}
{'ChapterName': 'B',
'ChapterNo': '2',
'Content': 'retete',
'Line': '2',
'Synonyms': 'retertret',
'Translation': 'retertert'}
>>>
看,妈妈,没用到xpath!