您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中基于XSD验证和填充XML中的默认值

在Python中基于XSD验证和填充XML中的默认值

为了跟进我的评论,这里有一些代码

from lxml import etree
from lxml.html import parse

schema_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:attributexs:complexType添加的架构命名空间。要填写您的认设置,您需要传递attribute_defaults=Trueetree.XMLParser(),它应该可以工作。

python 2022/1/1 18:45:10 有308人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶