使用lxml生成xml文件

2020-07-28  本文已影响0人  逸省
  1. 使用lxml库,可用pip直接安装
  2. 生成xml
from lxml import etree as ET
    
x = ET.Element('root')
ET.SubElement(x, 'body').text = 'sample'
    
xml_str = ET.tostring(x).decode()
print(xml_str)

  1. 添加命名空间
from lxml import etree as ET
    
ns = {"dc" : 'http://purl.org/dc/elements/1.1',
      "xlink" : 'http://www.w3.org/1999/xlink'}
    
x = ET.Element('root', nsmap = ns)
ET.SubElement(x, '{http://purl.org/dc/elements/1.1}body').text = 'sample'
    
xml_str = ET.tostring(x).decode()
print(xml_str)

输出为

<root xmlns:dc="http://purl.org/dc/elements/1.1" xmlns:xlink="http://www.w3.org/1999/xlink"><dc:body>sample</dc:body></root>
  1. 检查XML文件
schema_doc = ET.parse(schema_file)
schema = ET.XMLSchema(schema_doc)

data = DT.parse(data_file)
print(schema.validate(data))
print(schema.error_log)
上一篇下一篇

猜你喜欢

热点阅读