Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

python - How can I strip namespaces out of an lxml tree?

Following on from Removing child elements in XML using python ...

Thanks to @Tichodroma, I have this code:

If you can use lxml, try this:

 import lxml.etree

 tree = lxml.etree.parse("leg.xml")
 for dog in tree.xpath("//Leg1:Dog",
                       namespaces={"Leg1": "http://what.not"}):
     parent = dog.xpath("..")[0]
     parent.remove(dog)
     parent.text = None
 tree.write("leg.out.xml")

Now leg.out.xml looks like this:

 <?xml version="1.0"?>
 <Leg1:MOR xmlns:Leg1="http://what.not" oCount="7">
   <Leg1:Order>
     <Leg1:CTemp id="FO">
       <Leg1:Group bNum="001" cCount="4"/>
       <Leg1:Group bNum="002" cCount="4"/>
     </Leg1:CTemp>
     <Leg1:CTemp id="GO">
       <Leg1:Group bNum="001" cCount="4"/>
       <Leg1:Group bNum="002" cCount="4"/>
     </Leg1:CTemp>
   </Leg1:Order>
 </Leg1:MOR>

How do I modify my code to remove the Leg1: namespace prefix from all of the elements' tag names?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One possible way to remove namespace prefix from each element :

def strip_ns_prefix(tree):
    #iterate through only element nodes (skip comment node, text node, etc) :
    for element in tree.xpath('descendant-or-self::*'):
        #if element has prefix...
        if element.prefix:
            #replace element name with its local name
            element.tag = etree.QName(element).localname
    return tree

Another version which has namespace checking in the xpath instead of using if statement :

def strip_ns_prefix(tree):
    #xpath query for selecting all element nodes in namespace
    query = "descendant-or-self::*[namespace-uri()!='']"
    #for each element returned by the above xpath query...
    for element in tree.xpath(query):
        #replace element name with its local name
        element.tag = etree.QName(element).localname
    return tree

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...