Python:使用lxml添加xml架构属性

时间:2013-03-12 18:33:45

标签: python xsd lxml

我编写了一个脚本,以xml格式打印出当前目录中的所有.xml文件,但我无法弄清楚如何将xmlns属性添加到顶级标记中。 我想得到的输出是:

<?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>

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

 <?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

我在网上找到了一些明确设置命名空间属性的示例herehere,但说实话,我刚刚开始时,他们有点过头了。有没有其他方法将这些xmlns属性添加到databaseChangeLog标记?

1 个答案:

答案 0 :(得分:8)

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>