python添加lxml库,Python:使用lxml添加xml模式属性

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:

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

However, here is the output I am getting:

Here is my script:

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

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'))

yields

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值