【问题标题】:Type of an attribute in an xml file with lxml带有 lxml 的 xml 文件中的属性类型
【发布时间】:2012-05-10 16:45:10
【问题描述】:

我使用 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。我如何获得属性的类型?

【问题讨论】:

    标签: python types attributes xsd lxml


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 2021-09-07
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      相关资源
      最近更新 更多