无法绑定到具有嵌套(匿名)类型的pyxb类

2024-05-15 08:10:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我遵循了this thread中的说明,并从以下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>

我使用this tool online创建了以下XSD模式。在

^{pr2}$

然后我在shell中调用了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'。在

The documentation讨论了anonymous types这似乎与我的问题有关,但我还是无法使其发挥作用:

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

我得到错误MixedContentError: invalid non-element content

如何填写此XML?在


Tags: noimportreportidfooschemamy错误
1条回答
网友
1楼 · 发布于 2024-05-15 08:10:20

非规范化模式很困难,您可能需要尝试几种方法来提供所需的信息。下面是一个带注释的示例,虽然我使用的是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')

相关问题 更多 >