Невозможно привязать к классам pyxb вложенные (анонимные) типы

Я следовал инструкциям из этой темы и из этого XML:

<?xml version="1.0" encoding="UTF-8" ?>
<my_report>    
<something>
<foo>
Yes
</foo>
</something>

<something_else>
<id>4</id>
<foo>Finally</foo>
<score>0.2</score>
</something_else>    
</my_report>

Я создал следующую схему XSD, используя этот инструмент онлайн.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="my_report">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="something">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="foo"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="something_else">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:byte" name="id"/>
              <xs:element type="xs:string" name="foo"/>
              <xs:element type="xs:float" name="score"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Я тогда позвонил pyxben -u my_schema.csd -m my_schema в оболочке, а затем попытался использовать привязки объектов сборки:

from my_schema import my_report
my_xml_report = my_report()

Это, кажется, работает до сих пор (я могу получить доступ my_xml_report.something). Тем не менее, когда я пытаюсь заполнить вложенный элемент:

my_xml_report.something.foo = "No"

Я получаю ошибку 'NoneType'object has no atttribute 'foo',

Документация говорит о anonymous types которые, кажется, связаны с моей проблемой, но я все еще не могу заставить это работать:

import pyxb
my_xml_report.something = pyxb.BIND('foo', "No")

Я получаю ошибку MixedContentError: invalid non-element content

Как я могу заполнить этот XML?

1 ответ

Денормализованная схема сложна, и вам может понадобиться попробовать несколько подходов для предоставления необходимой информации. Вот аннотированный пример, хотя я использую PyXB 1.2.3, поэтому возможности могут быть немного более полными:

import pyxb
import my_schema

rep = my_schema.my_report()

# The something element here is very simple, with a single string
# element.  For the inner string element foo PyXB can figure things
# out for itself.  For the outer element it needs help.
#
# In a normalized schema where the type of something was tSomething,
# you would do:
#
#   rep.something = tSomething('yes')
#
# Without a tSomething easily reachable, to build it up piece-by-piece
# you could do:
rep.something = pyxb.BIND()  # Create an instance of whatever type satisfies something
rep.something.foo = 'yes'    # Assign to the foo element of what got created

# You can then optimize.  Here pyxb.BIND substitutes for the something
# element wrapper around that string, and figures out for itself that
# the "yes" can only go in the foo element:
rep.something = pyxb.BIND('yes')

# In fact, sometimes PyXB can even figure out the intermediate
# intermediate layers:
rep.something = 'yes'
# No more than two of them, though (and the lowest must be a simple type).

# Similarly here pyxb.BIND substitutes for the type of the
# something_else element.  Again the inner content is unambiguous and
# sequential, so the values can be provided in the constructor.
rep.something_else = pyxb.BIND(4, 'finally', 0.2)

print rep.toxml('utf-8')
Другие вопросы по тегам