美文网首页
使用lxml生成xml文件

使用lxml生成xml文件

作者: 逸省 | 来源:发表于2020-07-28 14:52 被阅读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)
    

    相关文章

      网友评论

          本文标题:使用lxml生成xml文件

          本文链接:https://www.haomeiwen.com/subject/rrmfrktx.html