簡體   English   中英

使用元素樹讀取xml文件

[英]Reading an xml file using element tree

我有一個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'`

現在我想獲取所有的ChapterNo,ChapterName等,分別使用元素樹,我想將這些數據插入數據庫中。...有人可以幫助我嗎?

RGDS,

Nimmy

要解析簡單的兩級數據結構並為每個組組合一個字典,您需要做的是:

>>> # 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!

ChapterNo不是root的直接子代,因此root.find('ChapterNo')將不起作用。 您將需要使用xpath語法來查找數據。

另外,有多次出現的ChapterNo,ChapterName等,因此您應該使用findall並遍歷結果以獲取每個文本。

chapter_nos = [e.text for e in root.findall('.//ChapterNo')]

等等。

這是一個使用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數據中測試了此代碼,並且工作正常,可以將所有內容插入數據庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM