默认命名空间和前缀命名空间共享相同的 URI。
.XML:
<Envelope xmlns="http://www.ibm.com/mdm/schema" xmlns:sch="http://www.ibm.com/mdm/schema">
<sch:requesterName>cusadmin</sch:requesterName>
<sch:requesterLanguage>100</sch:requesterLanguage>
<sch:requestOrigin>QAOffshore</sch:requestOrigin>
<QuestionId>472</QuestionId>
</Envelope>
我需要从元素标签中单独删除默认命名空间。 由于默认命名空间 URI 和前缀命名空间 URI 相同,因此以下代码也会删除带前缀的命名空间:(
我的代码:
from lxml import etree
import re
df_temp1=[]
root_ns=etree.iterparse(open("D:\Sample_data\XML\data_stack.xml",'r'),events=['start-ns'])
for _, node in root_ns:
if(node[0]==''):
df_temp1.append(node[1])
tree=etree.parse(open("D:\Sample_data\XML\data_stack.xml",'r'))
for e in tree.iter():
#if element has default namespace--remove the default namespace
if '{' in e.tag:
names = e.tag.split('}', 1)[0]
names1=re.sub("[{}]","",names)
if(names1 in df_temp1):
e.tag=e.tag.split('}', 1)[1]
print e.tag
输出:
Envelope
requesterName
requesterLanguage
requestOrigin
QuestionId
预期成果:
Envelope
{http://www.ibm.com/mdm/schema}requesterName
{http://www.ibm.com/mdm/schema}requesterLanguage
{http://www.ibm.com/mdm/schema}requestOrigin
QuestionId
关于如何获得此预期输出的任何想法?
为了删除命名空间前缀"sch",您必须像下面这样注册命名空间-
ET.register_namespace('', "http://www.ibm.com/mdm/schema")