如何从xml中读出标签?

时间:2012-06-20 16:34:48

标签: python xml elementtree

我从这个xml中读出信息时遇到了一些问题:

<entry number="50" date="2011-01-29">
 <name>Info text about account</name>
 <row account="1930" debit="0" credit="2051"/>
 <row account="1471" debit="410" credit="0"/>
 <row account="4404" debit="1641" credit="0"/>
</entry>

我使用此代码

def printInfoOfVerification():
    valFound = 0
        print("Now system will print information about a verification nr in xml:")
        val = input("Enter verification number: ")
    verificationNumbr = xmltree.iter('entry')
    for i in verificationNumbr:
        if (i.attrib['number']) == val:
                valFound = 1
                    print("Verification number:",val, "found")
                    print("Info about verification:")
                    print(i.attrib['date'])
            if valFound == 0:
                    print("Verification number not found:",val)

如果“val”= 50,则会产生:

Verification number: 50 found
Info about verification:
2011-01-29

但问题是,我还想在标签“name”中打印信息,所以对于这个例子,它应该是这样的:

Verification number: 50 found
Info about verification:
2011-01-29
Info text about account

我试图用xmltree.iter('name')和其他方式读取名称标签,但没有成功:(有谁知道怎么做? THX

2 个答案:

答案 0 :(得分:1)

我个人选择使用lxml和Python 2.7.x。

from lxml import etree

data = """
<entry number="50" date="2011-01-29">
 <name>Info text about account</name>
 <row account="1930" debit="0" credit="2051"/>
 <row account="1471" debit="410" credit="0"/>
 <row account="4404" debit="1641" credit="0"/>
</entry>
"""

tree = etree.fromstring(data)
entry = tree.xpath('/entry[@number="49"]')
if not entry:
    print 'No entry found'

entry = tree.xpath('/entry[@number="50"]')[0]
print 'found'
print 'Info: {}'.format(entry.get('date'))
print entry.find('name').text
for row in entry.findall('row'):
    print 'account =', row.get('account') # etc...

输出:

No entry found
found
Info: 2011-01-29
Info text about account
account = 1930
account = 1471
account = 4404

可能的方便查找(通过号码快速访问节点):

lookup = dict( (int(node.get('number')), node) for node in tree.xpath('/entry') )

然后通过:

访问
lookup[50].findall('account')

等...

答案 1 :(得分:0)

帮助!!我还找到了一种使用ElementTree来解决问题的方法,该问题使得这个打印出来了:

Verification number: 50 found
Info about verification:
2011-01-29
Namn: Info text about account
Konto: 1930, Debit:     0, Kredit:  2051
Konto: 1471, Debit:   410, Kredit:     0
Konto: 4404, Debit:  1641, Kredit:     0

我使用的代码:

def printInfoOfVerification():
        print("Now system will print information about a verification nr in xml:")
        val = input("Enter verification number: ")
        verificationNumbr = xmltree.iter('entry')
        for entry in verificationNumbr:
                if (entry.attrib['number']) == val:
                        valFound = 1
                        print("Verification number:",val, "found")
                        print("Info about verification:")
                        print(entry.attrib['date'])
                        findInfoAboutVerification(entry)
        if valFound == 0:
                print("Verification number not found:",val)


def findInfoAboutVerification(entry):
        verificationText = entry.iter()
        for node in verificationText:
                if "name" in node.tag:
                        print('Namn: %s' % node.text)
                if "comment" in node.tag:
                        print('Kommentar: %s' % node.text)
                if "row" in node.tag:
                        print('Konto: %s, Debit: %s, Kredit: %s' % (node.attrib['account'], node.attrib['debit'].rjust(5), node.attrib['credit'].rjust(5)))