Python:使用lxml添加xml架构属性 [英] Python: adding xml schema attributes with lxml

查看:306
本文介绍了Python:使用lxml添加xml架构属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,该脚本以xml格式打印出当前目录中的所有.xml文件,但是我不知道如何将xmlns属性添加到顶级标签. 我想得到的输出是:

I've written a script that prints out all the .xml files in the current directory in xml format, but I can't figure out how to add the xmlns attributes to the top-level tag. The output I want to get is:

<?xml version='1.0' encoding='utf-8'?>
<databaseChangeLog 
      xmlns="http://www.host.org/xml/ns/dbchangelog"
      xmlns:xsi="http://www.host.org/2001/XMLSchema-instance"
      xsi:schemaLocation="www.host.org/xml/ns/dbchangelog">

    <include file="cats.xml"/>
    <include file="dogs.xml"/>
    <include file="fish.xml"/>
    <include file="meerkats.xml"/>

</databaseChangLog>

但是,这是我得到的输出:

However, here is the output I am getting:

 <?xml version='1.0' encoding='utf-8'?>
 <databaseChangeLog>
    <include file="cats.xml"/>
    <include file="dogs.xml"/>
    <include file="fish.xml"/>
    <include file="meerkats.xml"/>
 </databaseChangLog>

这是我的剧本:

import lxml.etree
import lxml.builder
import glob

E = lxml.builder.ElementMaker()
ROOT = E.databaseChangeLog
DOC = E.include

# grab all the xml files
files = [DOC(file=f) for f in glob.glob("*.xml")]
the_doc = ROOT(*files)

str = lxml.etree.tostring(the_doc, pretty_print=True, xml_declaration=True, encoding='utf-8')

print str

我在网上找到了一些明确设置名称空间属性的示例,此处此处,但要老实说,当我刚开始时,他们对我有些不满.还有另一种方法可以将这些xmlns属性添加到databaseChangeLog标记中吗?

I've found some examples online of explicitly setting namespace attributes, here and here, but to be honest they went a little over my head as I am just starting out. Is there another way to add these xmlns attributes to the databaseChangeLog tag?

推荐答案

import lxml.etree as ET
import lxml.builder
import glob

dbchangelog = 'http://www.host.org/xml/ns/dbchangelog'
xsi = 'http://www.host.org/2001/XMLSchema-instance'
E = lxml.builder.ElementMaker(
    nsmap={
        None: dbchangelog,
        'xsi': xsi})

ROOT = E.databaseChangeLog
DOC = E.include

# grab all the xml files
files = [DOC(file=f) for f in glob.glob("*.xml")]

the_doc = ROOT(*files)
the_doc.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = 'www.host.org/xml/ns/dbchangelog'

print(ET.tostring(the_doc,
                  pretty_print=True, xml_declaration=True, encoding='utf-8'))

收益

<?xml version='1.0' encoding='utf-8'?>
<databaseChangeLog xmlns:xsi="http://www.host.org/2001/XMLSchema-instance" xmlns="http://www.host.org/xml/ns/dbchangelog" xsi:schemaLocation="www.host.org/xml/ns/dbchangelog">
  <include file="test.xml"/>
</databaseChangeLog>

这篇关于Python:使用lxml添加xml架构属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆