PyXB为生成的Python类添加anyAttribute属性

1 投票
1 回答
581 浏览
提问于 2025-04-18 08:39

给定这个结构:

<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
    <xs:anyAttribute/>
  </xs:complexType>
</xs:element>

在运行 pyxb -u <filename> -m person 命令后,如何使用生成的绑定来创建带有任意属性的 XML。

import person

p = person()
p.firstname = 'bob'
p.lastname  = 'bobbington'

#I want behavior like this
p.middlename = 'bobby'

#I would settle for behavior like this:
p.add_attribute( 'middlename', 'bobby' )

#Heck*, I'd even settle for:
temp_attr = pyxb.AttributeUse( name, value, blah, blah, blay )
p._AttributeMap.update( temp_attr.name(), temp_attr )

但是无论我尝试什么,当我调用 p.toxml() 时,临时属性都无法显示出来。

这是不支持的吗?还是我忽略了什么?

编辑:已经去掉了脏话。

编辑:找到了一种变通方法(语法和变量名可能不太对,但希望能帮助其他人理解)。

class PersonType():
    '''
    regular generated PersonType stuff here
    '''
    def add_attribute(self, name, value):
        t = pyxb.blahblahblah._AttributeUse(
            pyxb.blahblahblah._ExtendedName( None, attr_name),
            attr_name,
            pyxb.blahblah.StringDataType)
        t.setValue(self, value)  # or maybe _setValue
        self._AttributeMap[t.name()] = t

1 个回答

2

如果一个复杂类型支持通配符属性,那么这个类型的实例会有一个方法叫做 wildcardAttributeMap()。这个方法会返回一个映射表,里面是扩展名称和对应的属性值(用unicode字符串表示)之间的关系。根据 这个问题,目前没有公开的接口可以直接操作这个映射表,不过你可能可以手动进行操作。

根据我对你问题的理解,我添加了 这个问题,确认即使你把通配符属性放进了这个映射表,它们在生成的XML中也不会显示出来。

很抱歉这样。看起来是时候进行一次PyXB的bug修复了。

撰写回答