Skip to main content
 首页 » 编程设计

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

2025年05月04日9kerrycode

我使用 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 所基于的)中,属性是元素的属性,当您请求属性值时,您会得到字符串。