继续Removing child elements in XML using python ...
感谢@Tichodroma,我有这段代码:
如果您可以使用lxml,请尝试以下操作:
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")
现在leg.out.xml
看起来像这样:
<?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>
如何修改我的代码以从所有元素的标记名称中删除Leg1:
名称空间前缀?
答案 0 :(得分:9)
从每个元素中删除名称空间前缀的一种可能方法:
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
另一个在xpath中使用命名空间检查而不是使用if
语句的版本:
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