使用lxml生成xml文件

  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)

输出为

sample
  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)

你可能感兴趣的:(使用lxml生成xml文件)