繁体   English   中英

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

[英]Python: adding xml schema attributes with 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

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

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM