为了跟进我的评论,这里有一些代码
from lxml import etreefrom lxml.html import parseschema_root = etree.XML('''<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="c" default="1" type="xs:string"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType></xs:element></xs:schema>''')xmls = '''<a> <b/> <b c="2"/></a>'''schema = etree.XMLSchema(schema_root)parser = etree.XMLParser(schema = schema, attribute_defaults = True)root = etree.fromstring(xmls, parser)result = etree.tostring(root, pretty_print=True, method="xml")print result会给你
<a> <b c="1"/> <b c="2"/></a>
我稍微修改您的XSD,裹
xs:attribute在
xs:complexType和添加的架构命名空间。要填写您的默认设置,您需要传递
attribute_defaults=True给
etree.XMLParser(),它应该可以工作。



