【问题标题】:Default namespace and prefixed namespace sharing same URI - Need to remove default namespace URI alone from element using python默认命名空间和前缀命名空间共享相同的 URI - 需要使用 python 从元素中单独删除默认命名空间 URI
【发布时间】:2017-06-10 10:45:44
【问题描述】:

默认命名空间和前缀命名空间共享相同的 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

知道如何获得这个预期的输出吗?

【问题讨论】:

  • 如果唯一的变化是删除了默认命名空间声明 (xmlns="http://www.ibm.com/mdm/schema"),那么根元素将不在任何命名空间中,{http://www.ibm.com/mdm/schema}Envelope 不能成为预期结果的一部分。
  • @mzjn 是的,你是对的。我已经改变了预期的结果......
  • 我建议一个简单的文本搜索和替换操作,类似于这个:stackoverflow.com/a/40978913/407651

标签: xml python-2.7 lxml xml-namespaces


【解决方案1】:

为了删除你的命名空间前缀“sch”,你必须像下面这样注册命名空间-

ET.register_namespace('', "http://www.ibm.com/mdm/schema")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    相关资源
    最近更新 更多