0

The default Namespace and prefixed namespace shares same 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>

I need to remove the default namespace alone from the element tag. since both default and prefixed namespace uri are same, the following code removes prefixed namespace too.:(

My code:

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

Output:

Envelope
requesterName
requesterLanguage
requestOrigin
QuestionId

Expected Result:

Envelope
{http://www.ibm.com/mdm/schema}requesterName
{http://www.ibm.com/mdm/schema}requesterLanguage
{http://www.ibm.com/mdm/schema}requestOrigin
QuestionId

Any idea on how to get this expected output?

mariz
  • 509
  • 1
  • 7
  • 13
  • If the only change is that the default namespace declaration (`xmlns="http://www.ibm.com/mdm/schema"`) is removed, then the root element won't be in any namespace, and `{http://www.ibm.com/mdm/schema}Envelope` cannot be part of the expected result. – mzjn Jan 25 '17 at 17:04
  • @mzjn yes, you are right.I have changed the expected result... – mariz Jan 27 '17 at 05:12
  • I suggest a simple textual search and replace operation, similar to this one: http://stackoverflow.com/a/40978913/407651. – mzjn Jan 28 '17 at 16:53

1 Answers1

0

In order to remove your namespace prefix "sch" you have to register the namespace like below-

ET.register_namespace('', "http://www.ibm.com/mdm/schema")
IRSHAD
  • 2,855
  • 30
  • 39