使用lxm的xml文件中属性的类型

2024-07-05 07:58:50 发布

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

im使用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

^{pr2}$

然后是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。怎样才能得到属性的类型?在


Tags: 文件代码self类型属性schematypelxml
1条回答
网友
1楼 · 发布于 2024-07-05 07:58:50

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

^{}API具有“类型化”元素类(例如IntElement),但没有表示属性的类。在lxml(以及lxml所基于的ElementTree)中,属性是元素的属性,当你请求属性值时,你会得到字符串。在

相关问题 更多 >