如何使用dexml解析Python中的嵌套元素

时间:2016-05-05 18:54:53

标签: python xml

我正在尝试使用dexml解析以下xml:

<ticketDetail>
        <ticketId>int</ticketId>
.....
      </ticketDetail>
      <participants>
        <ParticipantDetailExt>
          <participantId>int</participantId>
...
        </ParticipantDetailExt>
        <ParticipantDetailExt>
          <participantId>int</participantId>
...
        </ParticipantDetailExt>
      </participants>

我的模型如下:

# Participant Class
class Participant(dexml.Model):
    class meta:
        tagname = "ParticipantDetailExt"

    participantId = fields.Integer(tagname='participantId')
...

# Ticket Class
class Ticket(dexml.Model):
    class meta:
        namespace = "Namespace Here"
        tagname = "ticketDetail"

    ticketId = fields.String(tagname='ticketId')
    ...
    participants = fields.List(Participant)

但是,虽然所有未嵌套的元素都正确解析,但参与者不会被解析并加载到对象结构中。如何使用dexml对这种类型的结构进行建模?

以下是示例代码:

#!/usr/bin/env python3

import xml.etree.ElementTree as ET
import dexml
from dexml import fields

samplexml = """<ticketDetail>
    <ticketId>1</ticketId>
  <participants>
    <ParticipantDetailExt>
      <participantId>2</participantId>
    </ParticipantDetailExt>
    <ParticipantDetailExt>
      <participantId>3</participantId>
    </ParticipantDetailExt>
  </participants>
</ticketDetail>"""

class Participant(dexml.Model):
    class meta:
        tagname = "ParticipantDetailExt"

    participantId = fields.Integer(tagname='participantId')

class Ticket(dexml.Model):
    class meta:
        tagname = "ticketDetail"

    ticketId = fields.String(tagname='ticketId')
    participants = fields.List(Participant)


myTk = Ticket.parse(samplexml)
print(myTk.ticketId)
print(len(myTk.participants))

Output is:
1
0

Expected Output would be:
1
2

1 个答案:

答案 0 :(得分:0)

尝试将tagname添加到List()

participants = fields.List(Participant, tagname="participants")

示例程序:

import dexml
from dexml import fields

# Participant Class
class Participant(dexml.Model):
    class meta:
        tagname = "ParticipantDetailExt"

    participantId = fields.Integer(tagname='participantId')


# Ticket Class
class Ticket(dexml.Model):
    class meta:
        #namespace = "Namespace Here"
        tagname = "ticketDetail"

    ticketId = fields.String(tagname='ticketId')
    participants = fields.List(Participant, tagname="participants")

t = Ticket.parse('''
<ticketDetail>
        <ticketId>int</ticketId>
      <participants>
        <ParticipantDetailExt>
          <participantId>42</participantId>
        </ParticipantDetailExt>
        <ParticipantDetailExt>
          <participantId>74</participantId>
        </ParticipantDetailExt>
      </participants>
      </ticketDetail>
''')

assert len(t.participants) == 2