8

我编写了一个脚本,以 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

我在网上找到了一些明确设置命名空间属性的例子,这里这里,但老实说,当我刚刚开始时,它们让我有点不知所措。还有另一种方法可以将这些 xmlns 属性添加到 databaseChangeLog 标记中吗?

4

1 回答 1

9
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>
于 2013-03-12T19:26:22.373 回答