[英]How can I strip namespaces out of an lxml tree?
Following on from Removing child elements in XML using python ...继使用 python 删除 XML 中的子元素之后......
Thanks to @Tichodroma, I have this code:感谢@Tichodroma,我有这个代码:
If you can use lxml , try this:如果你可以使用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")
Now leg.out.xml
looks like this:现在
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>
How do I modify my code to remove the Leg1:
namespace prefix from all of the elements' tag names?如何修改我的代码以从所有元素的标签名称中删除
Leg1:
命名空间前缀?
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 :另一个版本在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.