python - 使用 lxml 的 xml 文件中的属性类型

标签 python types attributes xsd lxml

我使用 python 和 lxml 读取 xml 文件,这些文件针对 xsd 文件进行了验证。我想找出属性的 xs:type。

到目前为止我的代码: XSD

...      
<xs:complexType name="io" >
  <xs:attribute name="number" type="xs:decimal" use="optional" default="5.9"/>
</xs:complexType>
...

XML

...
<io number="1.1">
...

然后是Python代码:

with open(self.xmlSchemaFilename) as schema:
     xmlschema_doc = objectify.parse(schema)
self.xmlschema = etree.XMLSchema(xmlschema_doc)
parser = etree.XMLParser(schema = self.xmlschema,
               attribute_defaults = True, remove_blank_text=True)
with open(self.xmlFilename) as myfile:
    tree = objectify.parse(myfile, parser)  
    #this correctly asserts the type from the xsd
root = tree.getroot()
self.xmlRoot = objectify.fromstring(etree.tostring(root))
self.xmlschema.assertValid(self.xmlRoot)

现在我可以通过

访问所有子节点的类型
type(self.xmlRoot.child)

它从 xsd 返回正确的类型并得到类似

的内容
<type 'lxml.objectify.IntElement'>

但是对于我通过

访问的属性
self.xmlRoot.child.attrib['number']

无论 xsd 规范如何,类型始终为 str。我如何获得属性的类型?

最佳答案

我认为这是不可能的。我不介意被证明是错误的,但很难看出 lxml 如何提供有关属性类型的信息。

lxml.objectify API 具有“类型化”的 Element 类(例如 IntElement),但没有表示属性的类。在 lxml(和 ElementTree;lxml 所基于的)中,属性是元素的属性,当您请求属性值时,您会得到字符串。

关于python - 使用 lxml 的 xml 文件中的属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10538666/

相关文章:

python-3.x - python 3 从父方法调用子属性

python - Django 中的多对一关系

c++ - C++ 中的 Uint32 和 unsigned int 有什么区别?

types - 有没有办法约束仿函数的参数签名,以便参数可以为结构提供未指定的相等类型?

dart - Dart中的运行时类型检查-检查列表

python - python'function'对象没有属性'GzipFile'

r - 通过使用 igraph (R) 组合事件顶点的属性来创建边缘属性

python - 如何检查列表是否包含空元素?

python - 点击: how do I apply an action to all commands and subcommands but allow a command to opt-out?

python - 如何检查随机词是否与用户输入相同?